blob: 4c1fa10cc8ff9b9e2a738d26d83f0181ff161dbc [file] [log] [blame]
Chris Lattner53e677a2004-04-02 20:23:17 +00001//===- ScalarEvolution.cpp - Scalar Evolution Analysis ----------*- C++ -*-===//
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002//
Chris Lattner53e677a2004-04-02 20:23:17 +00003// The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00007//
Chris Lattner53e677a2004-04-02 20:23:17 +00008//===----------------------------------------------------------------------===//
9//
10// This file contains the implementation of the scalar evolution analysis
11// engine, which is used primarily to analyze expressions involving induction
12// variables in loops.
13//
14// There are several aspects to this library. First is the representation of
15// scalar expressions, which are represented as subclasses of the SCEV class.
16// These classes are used to represent certain types of subexpressions that we
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.
Misha Brukman2b37d7c2005-04-21 21:13:18 +000031//
Chris Lattner53e677a2004-04-02 20:23:17 +000032// 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//
Chris Lattner53e677a2004-04-02 20:23:17 +000036// 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
Chris Lattner0a7f98c2004-04-15 15:07:24 +000062#include "llvm/Analysis/ScalarEvolutionExpressions.h"
Chris Lattner53e677a2004-04-02 20:23:17 +000063#include "llvm/Constants.h"
64#include "llvm/DerivedTypes.h"
Chris Lattner673e02b2004-10-12 01:49:27 +000065#include "llvm/GlobalVariable.h"
Chris Lattner53e677a2004-04-02 20:23:17 +000066#include "llvm/Instructions.h"
John Criswella1156432005-10-27 15:54:34 +000067#include "llvm/Analysis/ConstantFolding.h"
Chris Lattner53e677a2004-04-02 20:23:17 +000068#include "llvm/Analysis/LoopInfo.h"
69#include "llvm/Assembly/Writer.h"
70#include "llvm/Transforms/Scalar.h"
71#include "llvm/Support/CFG.h"
Chris Lattner95255282006-06-28 23:17:24 +000072#include "llvm/Support/CommandLine.h"
Chris Lattnerb3364092006-10-04 21:49:37 +000073#include "llvm/Support/Compiler.h"
Chris Lattner53e677a2004-04-02 20:23:17 +000074#include "llvm/Support/ConstantRange.h"
75#include "llvm/Support/InstIterator.h"
Chris Lattnerb3364092006-10-04 21:49:37 +000076#include "llvm/Support/ManagedStatic.h"
Bill Wendling6f81b512006-11-28 22:46:12 +000077#include "llvm/Support/Streams.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000078#include "llvm/ADT/Statistic.h"
Bill Wendling6f81b512006-11-28 22:46:12 +000079#include <ostream>
Alkis Evlogimenos20aa4742004-09-03 18:19:51 +000080#include <algorithm>
Jeff Cohen97af7512006-12-02 02:22:01 +000081#include <cmath>
Chris Lattner53e677a2004-04-02 20:23:17 +000082using namespace llvm;
83
84namespace {
Chris Lattner5d8925c2006-08-27 22:30:17 +000085 RegisterPass<ScalarEvolution>
Chris Lattner45a1cf82004-04-19 03:42:32 +000086 R("scalar-evolution", "Scalar Evolution Analysis");
Chris Lattner53e677a2004-04-02 20:23:17 +000087
88 Statistic<>
89 NumBruteForceEvaluations("scalar-evolution",
Chris Lattner673e02b2004-10-12 01:49:27 +000090 "Number of brute force evaluations needed to "
91 "calculate high-order polynomial exit values");
92 Statistic<>
93 NumArrayLenItCounts("scalar-evolution",
94 "Number of trip counts computed with array length");
Chris Lattner53e677a2004-04-02 20:23:17 +000095 Statistic<>
96 NumTripCountsComputed("scalar-evolution",
97 "Number of loops with predictable loop counts");
98 Statistic<>
99 NumTripCountsNotComputed("scalar-evolution",
100 "Number of loops without predictable loop counts");
Chris Lattner7980fb92004-04-17 18:36:24 +0000101 Statistic<>
102 NumBruteForceTripCountsComputed("scalar-evolution",
103 "Number of loops with trip counts computed by force");
104
105 cl::opt<unsigned>
106 MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden,
Chris Lattnerbed21de2005-09-28 22:30:58 +0000107 cl::desc("Maximum number of iterations SCEV will "
108 "symbolically execute a constant derived loop"),
Chris Lattner7980fb92004-04-17 18:36:24 +0000109 cl::init(100));
Chris Lattner53e677a2004-04-02 20:23:17 +0000110}
111
112//===----------------------------------------------------------------------===//
113// SCEV class definitions
114//===----------------------------------------------------------------------===//
115
116//===----------------------------------------------------------------------===//
117// Implementation of the SCEV class.
118//
Chris Lattner53e677a2004-04-02 20:23:17 +0000119SCEV::~SCEV() {}
120void SCEV::dump() const {
Bill Wendling6f81b512006-11-28 22:46:12 +0000121 print(llvm_cerr);
Chris Lattner53e677a2004-04-02 20:23:17 +0000122}
123
124/// getValueRange - Return the tightest constant bounds that this value is
125/// known to have. This method is only valid on integer SCEV objects.
126ConstantRange SCEV::getValueRange() const {
127 const Type *Ty = getType();
128 assert(Ty->isInteger() && "Can't get range for a non-integer SCEV!");
129 Ty = Ty->getUnsignedVersion();
130 // Default to a full range if no better information is available.
131 return ConstantRange(getType());
132}
133
134
135SCEVCouldNotCompute::SCEVCouldNotCompute() : SCEV(scCouldNotCompute) {}
136
137bool SCEVCouldNotCompute::isLoopInvariant(const Loop *L) const {
138 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
Misha Brukmanbb2aff12004-04-05 19:00:46 +0000139 return false;
Chris Lattner53e677a2004-04-02 20:23:17 +0000140}
141
142const Type *SCEVCouldNotCompute::getType() const {
143 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
Misha Brukmanbb2aff12004-04-05 19:00:46 +0000144 return 0;
Chris Lattner53e677a2004-04-02 20:23:17 +0000145}
146
147bool SCEVCouldNotCompute::hasComputableLoopEvolution(const Loop *L) const {
148 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
149 return false;
150}
151
Chris Lattner4dc534c2005-02-13 04:37:18 +0000152SCEVHandle SCEVCouldNotCompute::
153replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
154 const SCEVHandle &Conc) const {
155 return this;
156}
157
Chris Lattner53e677a2004-04-02 20:23:17 +0000158void SCEVCouldNotCompute::print(std::ostream &OS) const {
159 OS << "***COULDNOTCOMPUTE***";
160}
161
162bool SCEVCouldNotCompute::classof(const SCEV *S) {
163 return S->getSCEVType() == scCouldNotCompute;
164}
165
166
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000167// SCEVConstants - Only allow the creation of one SCEVConstant for any
168// particular value. Don't use a SCEVHandle here, or else the object will
169// never be deleted!
Chris Lattnerb3364092006-10-04 21:49:37 +0000170static ManagedStatic<std::map<ConstantInt*, SCEVConstant*> > SCEVConstants;
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000171
Chris Lattner53e677a2004-04-02 20:23:17 +0000172
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000173SCEVConstant::~SCEVConstant() {
Chris Lattnerb3364092006-10-04 21:49:37 +0000174 SCEVConstants->erase(V);
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000175}
Chris Lattner53e677a2004-04-02 20:23:17 +0000176
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000177SCEVHandle SCEVConstant::get(ConstantInt *V) {
178 // Make sure that SCEVConstant instances are all unsigned.
179 if (V->getType()->isSigned()) {
180 const Type *NewTy = V->getType()->getUnsignedVersion();
Reid Spencer14bab5d2006-12-04 17:05:42 +0000181 V = cast<ConstantInt>(
Reid Spencer7858b332006-12-05 19:14:13 +0000182 ConstantExpr::getBitCast(V, NewTy));
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000183 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000184
Chris Lattnerb3364092006-10-04 21:49:37 +0000185 SCEVConstant *&R = (*SCEVConstants)[V];
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000186 if (R == 0) R = new SCEVConstant(V);
187 return R;
188}
Chris Lattner53e677a2004-04-02 20:23:17 +0000189
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000190ConstantRange SCEVConstant::getValueRange() const {
191 return ConstantRange(V);
192}
Chris Lattner53e677a2004-04-02 20:23:17 +0000193
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000194const Type *SCEVConstant::getType() const { return V->getType(); }
Chris Lattner53e677a2004-04-02 20:23:17 +0000195
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000196void SCEVConstant::print(std::ostream &OS) const {
197 WriteAsOperand(OS, V, false);
198}
Chris Lattner53e677a2004-04-02 20:23:17 +0000199
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000200// SCEVTruncates - Only allow the creation of one SCEVTruncateExpr for any
201// particular input. Don't use a SCEVHandle here, or else the object will
202// never be deleted!
Chris Lattnerb3364092006-10-04 21:49:37 +0000203static ManagedStatic<std::map<std::pair<SCEV*, const Type*>,
204 SCEVTruncateExpr*> > SCEVTruncates;
Chris Lattner53e677a2004-04-02 20:23:17 +0000205
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000206SCEVTruncateExpr::SCEVTruncateExpr(const SCEVHandle &op, const Type *ty)
207 : SCEV(scTruncate), Op(op), Ty(ty) {
208 assert(Op->getType()->isInteger() && Ty->isInteger() &&
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000209 "Cannot truncate non-integer value!");
210 assert(Op->getType()->getPrimitiveSize() > Ty->getPrimitiveSize() &&
211 "This is not a truncating conversion!");
212}
Chris Lattner53e677a2004-04-02 20:23:17 +0000213
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000214SCEVTruncateExpr::~SCEVTruncateExpr() {
Chris Lattnerb3364092006-10-04 21:49:37 +0000215 SCEVTruncates->erase(std::make_pair(Op, Ty));
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000216}
Chris Lattner53e677a2004-04-02 20:23:17 +0000217
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000218ConstantRange SCEVTruncateExpr::getValueRange() const {
219 return getOperand()->getValueRange().truncate(getType());
220}
Chris Lattner53e677a2004-04-02 20:23:17 +0000221
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000222void SCEVTruncateExpr::print(std::ostream &OS) const {
223 OS << "(truncate " << *Op << " to " << *Ty << ")";
224}
225
226// SCEVZeroExtends - Only allow the creation of one SCEVZeroExtendExpr for any
227// particular input. Don't use a SCEVHandle here, or else the object will never
228// be deleted!
Chris Lattnerb3364092006-10-04 21:49:37 +0000229static ManagedStatic<std::map<std::pair<SCEV*, const Type*>,
230 SCEVZeroExtendExpr*> > SCEVZeroExtends;
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000231
232SCEVZeroExtendExpr::SCEVZeroExtendExpr(const SCEVHandle &op, const Type *ty)
Reid Spencer48d8a702006-11-01 21:53:12 +0000233 : SCEV(scZeroExtend), Op(op), Ty(ty) {
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000234 assert(Op->getType()->isInteger() && Ty->isInteger() &&
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000235 "Cannot zero extend non-integer value!");
236 assert(Op->getType()->getPrimitiveSize() < Ty->getPrimitiveSize() &&
237 "This is not an extending conversion!");
238}
239
240SCEVZeroExtendExpr::~SCEVZeroExtendExpr() {
Chris Lattnerb3364092006-10-04 21:49:37 +0000241 SCEVZeroExtends->erase(std::make_pair(Op, Ty));
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000242}
243
244ConstantRange SCEVZeroExtendExpr::getValueRange() const {
245 return getOperand()->getValueRange().zeroExtend(getType());
246}
247
248void SCEVZeroExtendExpr::print(std::ostream &OS) const {
249 OS << "(zeroextend " << *Op << " to " << *Ty << ")";
250}
251
252// SCEVCommExprs - Only allow the creation of one SCEVCommutativeExpr for any
253// particular input. Don't use a SCEVHandle here, or else the object will never
254// be deleted!
Chris Lattnerb3364092006-10-04 21:49:37 +0000255static ManagedStatic<std::map<std::pair<unsigned, std::vector<SCEV*> >,
256 SCEVCommutativeExpr*> > SCEVCommExprs;
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000257
258SCEVCommutativeExpr::~SCEVCommutativeExpr() {
Chris Lattnerb3364092006-10-04 21:49:37 +0000259 SCEVCommExprs->erase(std::make_pair(getSCEVType(),
260 std::vector<SCEV*>(Operands.begin(),
261 Operands.end())));
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000262}
263
264void SCEVCommutativeExpr::print(std::ostream &OS) const {
265 assert(Operands.size() > 1 && "This plus expr shouldn't exist!");
266 const char *OpStr = getOperationStr();
267 OS << "(" << *Operands[0];
268 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
269 OS << OpStr << *Operands[i];
270 OS << ")";
271}
272
Chris Lattner4dc534c2005-02-13 04:37:18 +0000273SCEVHandle SCEVCommutativeExpr::
274replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
275 const SCEVHandle &Conc) const {
276 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
277 SCEVHandle H = getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc);
278 if (H != getOperand(i)) {
279 std::vector<SCEVHandle> NewOps;
280 NewOps.reserve(getNumOperands());
281 for (unsigned j = 0; j != i; ++j)
282 NewOps.push_back(getOperand(j));
283 NewOps.push_back(H);
284 for (++i; i != e; ++i)
285 NewOps.push_back(getOperand(i)->
286 replaceSymbolicValuesWithConcrete(Sym, Conc));
287
288 if (isa<SCEVAddExpr>(this))
289 return SCEVAddExpr::get(NewOps);
290 else if (isa<SCEVMulExpr>(this))
291 return SCEVMulExpr::get(NewOps);
292 else
293 assert(0 && "Unknown commutative expr!");
294 }
295 }
296 return this;
297}
298
299
Chris Lattner60a05cc2006-04-01 04:48:52 +0000300// SCEVSDivs - Only allow the creation of one SCEVSDivExpr for any particular
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000301// input. Don't use a SCEVHandle here, or else the object will never be
302// deleted!
Chris Lattnerb3364092006-10-04 21:49:37 +0000303static ManagedStatic<std::map<std::pair<SCEV*, SCEV*>,
304 SCEVSDivExpr*> > SCEVSDivs;
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000305
Chris Lattner60a05cc2006-04-01 04:48:52 +0000306SCEVSDivExpr::~SCEVSDivExpr() {
Chris Lattnerb3364092006-10-04 21:49:37 +0000307 SCEVSDivs->erase(std::make_pair(LHS, RHS));
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000308}
309
Chris Lattner60a05cc2006-04-01 04:48:52 +0000310void SCEVSDivExpr::print(std::ostream &OS) const {
311 OS << "(" << *LHS << " /s " << *RHS << ")";
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000312}
313
Chris Lattner60a05cc2006-04-01 04:48:52 +0000314const Type *SCEVSDivExpr::getType() const {
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000315 const Type *Ty = LHS->getType();
Chris Lattner60a05cc2006-04-01 04:48:52 +0000316 if (Ty->isUnsigned()) Ty = Ty->getSignedVersion();
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000317 return Ty;
318}
319
320// SCEVAddRecExprs - Only allow the creation of one SCEVAddRecExpr for any
321// particular input. Don't use a SCEVHandle here, or else the object will never
322// be deleted!
Chris Lattnerb3364092006-10-04 21:49:37 +0000323static ManagedStatic<std::map<std::pair<const Loop *, std::vector<SCEV*> >,
324 SCEVAddRecExpr*> > SCEVAddRecExprs;
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000325
326SCEVAddRecExpr::~SCEVAddRecExpr() {
Chris Lattnerb3364092006-10-04 21:49:37 +0000327 SCEVAddRecExprs->erase(std::make_pair(L,
328 std::vector<SCEV*>(Operands.begin(),
329 Operands.end())));
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000330}
331
Chris Lattner4dc534c2005-02-13 04:37:18 +0000332SCEVHandle SCEVAddRecExpr::
333replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
334 const SCEVHandle &Conc) const {
335 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
336 SCEVHandle H = getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc);
337 if (H != getOperand(i)) {
338 std::vector<SCEVHandle> NewOps;
339 NewOps.reserve(getNumOperands());
340 for (unsigned j = 0; j != i; ++j)
341 NewOps.push_back(getOperand(j));
342 NewOps.push_back(H);
343 for (++i; i != e; ++i)
344 NewOps.push_back(getOperand(i)->
345 replaceSymbolicValuesWithConcrete(Sym, Conc));
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000346
Chris Lattner4dc534c2005-02-13 04:37:18 +0000347 return get(NewOps, L);
348 }
349 }
350 return this;
351}
352
353
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000354bool SCEVAddRecExpr::isLoopInvariant(const Loop *QueryLoop) const {
355 // This recurrence is invariant w.r.t to QueryLoop iff QueryLoop doesn't
Chris Lattnerff2006a2005-08-16 00:37:01 +0000356 // contain L and if the start is invariant.
357 return !QueryLoop->contains(L->getHeader()) &&
358 getOperand(0)->isLoopInvariant(QueryLoop);
Chris Lattner53e677a2004-04-02 20:23:17 +0000359}
360
361
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000362void SCEVAddRecExpr::print(std::ostream &OS) const {
363 OS << "{" << *Operands[0];
364 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
365 OS << ",+," << *Operands[i];
366 OS << "}<" << L->getHeader()->getName() + ">";
367}
Chris Lattner53e677a2004-04-02 20:23:17 +0000368
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000369// SCEVUnknowns - Only allow the creation of one SCEVUnknown for any particular
370// value. Don't use a SCEVHandle here, or else the object will never be
371// deleted!
Chris Lattnerb3364092006-10-04 21:49:37 +0000372static ManagedStatic<std::map<Value*, SCEVUnknown*> > SCEVUnknowns;
Chris Lattner53e677a2004-04-02 20:23:17 +0000373
Chris Lattnerb3364092006-10-04 21:49:37 +0000374SCEVUnknown::~SCEVUnknown() { SCEVUnknowns->erase(V); }
Chris Lattner53e677a2004-04-02 20:23:17 +0000375
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000376bool SCEVUnknown::isLoopInvariant(const Loop *L) const {
377 // All non-instruction values are loop invariant. All instructions are loop
378 // invariant if they are not contained in the specified loop.
379 if (Instruction *I = dyn_cast<Instruction>(V))
380 return !L->contains(I->getParent());
381 return true;
382}
Chris Lattner53e677a2004-04-02 20:23:17 +0000383
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000384const Type *SCEVUnknown::getType() const {
385 return V->getType();
386}
Chris Lattner53e677a2004-04-02 20:23:17 +0000387
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000388void SCEVUnknown::print(std::ostream &OS) const {
389 WriteAsOperand(OS, V, false);
Chris Lattner53e677a2004-04-02 20:23:17 +0000390}
391
Chris Lattner8d741b82004-06-20 06:23:15 +0000392//===----------------------------------------------------------------------===//
393// SCEV Utilities
394//===----------------------------------------------------------------------===//
395
396namespace {
397 /// SCEVComplexityCompare - Return true if the complexity of the LHS is less
398 /// than the complexity of the RHS. This comparator is used to canonicalize
399 /// expressions.
Chris Lattner95255282006-06-28 23:17:24 +0000400 struct VISIBILITY_HIDDEN SCEVComplexityCompare {
Chris Lattner8d741b82004-06-20 06:23:15 +0000401 bool operator()(SCEV *LHS, SCEV *RHS) {
402 return LHS->getSCEVType() < RHS->getSCEVType();
403 }
404 };
405}
406
407/// GroupByComplexity - Given a list of SCEV objects, order them by their
408/// complexity, and group objects of the same complexity together by value.
409/// When this routine is finished, we know that any duplicates in the vector are
410/// consecutive and that complexity is monotonically increasing.
411///
412/// Note that we go take special precautions to ensure that we get determinstic
413/// results from this routine. In other words, we don't want the results of
414/// this to depend on where the addresses of various SCEV objects happened to
415/// land in memory.
416///
417static void GroupByComplexity(std::vector<SCEVHandle> &Ops) {
418 if (Ops.size() < 2) return; // Noop
419 if (Ops.size() == 2) {
420 // This is the common case, which also happens to be trivially simple.
421 // Special case it.
422 if (Ops[0]->getSCEVType() > Ops[1]->getSCEVType())
423 std::swap(Ops[0], Ops[1]);
424 return;
425 }
426
427 // Do the rough sort by complexity.
428 std::sort(Ops.begin(), Ops.end(), SCEVComplexityCompare());
429
430 // Now that we are sorted by complexity, group elements of the same
431 // complexity. Note that this is, at worst, N^2, but the vector is likely to
432 // be extremely short in practice. Note that we take this approach because we
433 // do not want to depend on the addresses of the objects we are grouping.
Chris Lattner2d584522004-06-20 17:01:44 +0000434 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
Chris Lattner8d741b82004-06-20 06:23:15 +0000435 SCEV *S = Ops[i];
436 unsigned Complexity = S->getSCEVType();
437
438 // If there are any objects of the same complexity and same value as this
439 // one, group them.
440 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
441 if (Ops[j] == S) { // Found a duplicate.
442 // Move it to immediately after i'th element.
443 std::swap(Ops[i+1], Ops[j]);
444 ++i; // no need to rescan it.
Chris Lattner541ad5e2004-06-20 20:32:16 +0000445 if (i == e-2) return; // Done!
Chris Lattner8d741b82004-06-20 06:23:15 +0000446 }
447 }
448 }
449}
450
Chris Lattner53e677a2004-04-02 20:23:17 +0000451
Chris Lattner53e677a2004-04-02 20:23:17 +0000452
453//===----------------------------------------------------------------------===//
454// Simple SCEV method implementations
455//===----------------------------------------------------------------------===//
456
457/// getIntegerSCEV - Given an integer or FP type, create a constant for the
458/// specified signed integer value and return a SCEV for the constant.
Chris Lattnerb06432c2004-04-23 21:29:03 +0000459SCEVHandle SCEVUnknown::getIntegerSCEV(int Val, const Type *Ty) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000460 Constant *C;
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000461 if (Val == 0)
Chris Lattner53e677a2004-04-02 20:23:17 +0000462 C = Constant::getNullValue(Ty);
463 else if (Ty->isFloatingPoint())
464 C = ConstantFP::get(Ty, Val);
465 else if (Ty->isSigned())
Reid Spencerb83eb642006-10-20 07:07:24 +0000466 C = ConstantInt::get(Ty, Val);
Chris Lattner53e677a2004-04-02 20:23:17 +0000467 else {
Reid Spencerb83eb642006-10-20 07:07:24 +0000468 C = ConstantInt::get(Ty->getSignedVersion(), Val);
Reid Spencer7858b332006-12-05 19:14:13 +0000469 C = ConstantExpr::getBitCast(C, Ty);
Chris Lattner53e677a2004-04-02 20:23:17 +0000470 }
471 return SCEVUnknown::get(C);
472}
473
474/// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion of the
475/// input value to the specified type. If the type must be extended, it is zero
476/// extended.
477static SCEVHandle getTruncateOrZeroExtend(const SCEVHandle &V, const Type *Ty) {
478 const Type *SrcTy = V->getType();
479 assert(SrcTy->isInteger() && Ty->isInteger() &&
480 "Cannot truncate or zero extend with non-integer arguments!");
481 if (SrcTy->getPrimitiveSize() == Ty->getPrimitiveSize())
482 return V; // No conversion
483 if (SrcTy->getPrimitiveSize() > Ty->getPrimitiveSize())
484 return SCEVTruncateExpr::get(V, Ty);
485 return SCEVZeroExtendExpr::get(V, Ty);
486}
487
488/// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V
489///
Chris Lattnerbac5b462005-03-09 05:34:41 +0000490SCEVHandle SCEV::getNegativeSCEV(const SCEVHandle &V) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000491 if (SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
492 return SCEVUnknown::get(ConstantExpr::getNeg(VC->getValue()));
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000493
Chris Lattnerb06432c2004-04-23 21:29:03 +0000494 return SCEVMulExpr::get(V, SCEVUnknown::getIntegerSCEV(-1, V->getType()));
Chris Lattner53e677a2004-04-02 20:23:17 +0000495}
496
497/// getMinusSCEV - Return a SCEV corresponding to LHS - RHS.
498///
Chris Lattnerbac5b462005-03-09 05:34:41 +0000499SCEVHandle SCEV::getMinusSCEV(const SCEVHandle &LHS, const SCEVHandle &RHS) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000500 // X - Y --> X + -Y
Chris Lattnerbac5b462005-03-09 05:34:41 +0000501 return SCEVAddExpr::get(LHS, SCEV::getNegativeSCEV(RHS));
Chris Lattner53e677a2004-04-02 20:23:17 +0000502}
503
504
Chris Lattner53e677a2004-04-02 20:23:17 +0000505/// PartialFact - Compute V!/(V-NumSteps)!
506static SCEVHandle PartialFact(SCEVHandle V, unsigned NumSteps) {
507 // Handle this case efficiently, it is common to have constant iteration
508 // counts while computing loop exit values.
509 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(V)) {
Reid Spencerb83eb642006-10-20 07:07:24 +0000510 uint64_t Val = SC->getValue()->getZExtValue();
Chris Lattner53e677a2004-04-02 20:23:17 +0000511 uint64_t Result = 1;
512 for (; NumSteps; --NumSteps)
513 Result *= Val-(NumSteps-1);
Reid Spencerb83eb642006-10-20 07:07:24 +0000514 Constant *Res = ConstantInt::get(Type::ULongTy, Result);
Reid Spencer14bab5d2006-12-04 17:05:42 +0000515 return SCEVUnknown::get(
Reid Spencer7858b332006-12-05 19:14:13 +0000516 ConstantExpr::getTruncOrBitCast(Res, V->getType()));
Chris Lattner53e677a2004-04-02 20:23:17 +0000517 }
518
519 const Type *Ty = V->getType();
520 if (NumSteps == 0)
Chris Lattnerb06432c2004-04-23 21:29:03 +0000521 return SCEVUnknown::getIntegerSCEV(1, Ty);
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000522
Chris Lattner53e677a2004-04-02 20:23:17 +0000523 SCEVHandle Result = V;
524 for (unsigned i = 1; i != NumSteps; ++i)
Chris Lattnerbac5b462005-03-09 05:34:41 +0000525 Result = SCEVMulExpr::get(Result, SCEV::getMinusSCEV(V,
Chris Lattnerb06432c2004-04-23 21:29:03 +0000526 SCEVUnknown::getIntegerSCEV(i, Ty)));
Chris Lattner53e677a2004-04-02 20:23:17 +0000527 return Result;
528}
529
530
531/// evaluateAtIteration - Return the value of this chain of recurrences at
532/// the specified iteration number. We can evaluate this recurrence by
533/// multiplying each element in the chain by the binomial coefficient
534/// corresponding to it. In other words, we can evaluate {A,+,B,+,C,+,D} as:
535///
536/// A*choose(It, 0) + B*choose(It, 1) + C*choose(It, 2) + D*choose(It, 3)
537///
538/// FIXME/VERIFY: I don't trust that this is correct in the face of overflow.
539/// Is the binomial equation safe using modular arithmetic??
540///
541SCEVHandle SCEVAddRecExpr::evaluateAtIteration(SCEVHandle It) const {
542 SCEVHandle Result = getStart();
543 int Divisor = 1;
544 const Type *Ty = It->getType();
545 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
546 SCEVHandle BC = PartialFact(It, i);
547 Divisor *= i;
Chris Lattner60a05cc2006-04-01 04:48:52 +0000548 SCEVHandle Val = SCEVSDivExpr::get(SCEVMulExpr::get(BC, getOperand(i)),
Chris Lattnerb06432c2004-04-23 21:29:03 +0000549 SCEVUnknown::getIntegerSCEV(Divisor,Ty));
Chris Lattner53e677a2004-04-02 20:23:17 +0000550 Result = SCEVAddExpr::get(Result, Val);
551 }
552 return Result;
553}
554
555
556//===----------------------------------------------------------------------===//
557// SCEV Expression folder implementations
558//===----------------------------------------------------------------------===//
559
560SCEVHandle SCEVTruncateExpr::get(const SCEVHandle &Op, const Type *Ty) {
561 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
Reid Spencer7858b332006-12-05 19:14:13 +0000562 return SCEVUnknown::get(
563 ConstantExpr::getTruncOrBitCast(SC->getValue(), Ty));
Chris Lattner53e677a2004-04-02 20:23:17 +0000564
565 // If the input value is a chrec scev made out of constants, truncate
566 // all of the constants.
567 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
568 std::vector<SCEVHandle> Operands;
569 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
570 // FIXME: This should allow truncation of other expression types!
571 if (isa<SCEVConstant>(AddRec->getOperand(i)))
572 Operands.push_back(get(AddRec->getOperand(i), Ty));
573 else
574 break;
575 if (Operands.size() == AddRec->getNumOperands())
576 return SCEVAddRecExpr::get(Operands, AddRec->getLoop());
577 }
578
Chris Lattnerb3364092006-10-04 21:49:37 +0000579 SCEVTruncateExpr *&Result = (*SCEVTruncates)[std::make_pair(Op, Ty)];
Chris Lattner53e677a2004-04-02 20:23:17 +0000580 if (Result == 0) Result = new SCEVTruncateExpr(Op, Ty);
581 return Result;
582}
583
584SCEVHandle SCEVZeroExtendExpr::get(const SCEVHandle &Op, const Type *Ty) {
585 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
Reid Spencer7858b332006-12-05 19:14:13 +0000586 return SCEVUnknown::get(
587 ConstantExpr::getZExtOrBitCast(SC->getValue(), Ty));
Chris Lattner53e677a2004-04-02 20:23:17 +0000588
589 // FIXME: If the input value is a chrec scev, and we can prove that the value
590 // did not overflow the old, smaller, value, we can zero extend all of the
591 // operands (often constants). This would allow analysis of something like
592 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
593
Chris Lattnerb3364092006-10-04 21:49:37 +0000594 SCEVZeroExtendExpr *&Result = (*SCEVZeroExtends)[std::make_pair(Op, Ty)];
Chris Lattner53e677a2004-04-02 20:23:17 +0000595 if (Result == 0) Result = new SCEVZeroExtendExpr(Op, Ty);
596 return Result;
597}
598
599// get - Get a canonical add expression, or something simpler if possible.
600SCEVHandle SCEVAddExpr::get(std::vector<SCEVHandle> &Ops) {
601 assert(!Ops.empty() && "Cannot get empty add!");
Chris Lattner627018b2004-04-07 16:16:11 +0000602 if (Ops.size() == 1) return Ops[0];
Chris Lattner53e677a2004-04-02 20:23:17 +0000603
604 // Sort by complexity, this groups all similar expression types together.
Chris Lattner8d741b82004-06-20 06:23:15 +0000605 GroupByComplexity(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +0000606
607 // If there are any constants, fold them together.
608 unsigned Idx = 0;
609 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
610 ++Idx;
Chris Lattner627018b2004-04-07 16:16:11 +0000611 assert(Idx < Ops.size());
Chris Lattner53e677a2004-04-02 20:23:17 +0000612 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
613 // We found two constants, fold them together!
614 Constant *Fold = ConstantExpr::getAdd(LHSC->getValue(), RHSC->getValue());
615 if (ConstantInt *CI = dyn_cast<ConstantInt>(Fold)) {
616 Ops[0] = SCEVConstant::get(CI);
617 Ops.erase(Ops.begin()+1); // Erase the folded element
618 if (Ops.size() == 1) return Ops[0];
Chris Lattner7ffc07d2005-02-26 18:50:19 +0000619 LHSC = cast<SCEVConstant>(Ops[0]);
Chris Lattner53e677a2004-04-02 20:23:17 +0000620 } else {
621 // If we couldn't fold the expression, move to the next constant. Note
622 // that this is impossible to happen in practice because we always
623 // constant fold constant ints to constant ints.
624 ++Idx;
625 }
626 }
627
628 // If we are left with a constant zero being added, strip it off.
629 if (cast<SCEVConstant>(Ops[0])->getValue()->isNullValue()) {
630 Ops.erase(Ops.begin());
631 --Idx;
632 }
633 }
634
Chris Lattner627018b2004-04-07 16:16:11 +0000635 if (Ops.size() == 1) return Ops[0];
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000636
Chris Lattner53e677a2004-04-02 20:23:17 +0000637 // Okay, check to see if the same value occurs in the operand list twice. If
638 // so, merge them together into an multiply expression. Since we sorted the
639 // list, these values are required to be adjacent.
640 const Type *Ty = Ops[0]->getType();
641 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
642 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
643 // Found a match, merge the two values into a multiply, and add any
644 // remaining values to the result.
Chris Lattnerb06432c2004-04-23 21:29:03 +0000645 SCEVHandle Two = SCEVUnknown::getIntegerSCEV(2, Ty);
Chris Lattner53e677a2004-04-02 20:23:17 +0000646 SCEVHandle Mul = SCEVMulExpr::get(Ops[i], Two);
647 if (Ops.size() == 2)
648 return Mul;
649 Ops.erase(Ops.begin()+i, Ops.begin()+i+2);
650 Ops.push_back(Mul);
651 return SCEVAddExpr::get(Ops);
652 }
653
654 // Okay, now we know the first non-constant operand. If there are add
655 // operands they would be next.
656 if (Idx < Ops.size()) {
657 bool DeletedAdd = false;
658 while (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
659 // If we have an add, expand the add operands onto the end of the operands
660 // list.
661 Ops.insert(Ops.end(), Add->op_begin(), Add->op_end());
662 Ops.erase(Ops.begin()+Idx);
663 DeletedAdd = true;
664 }
665
666 // If we deleted at least one add, we added operands to the end of the list,
667 // and they are not necessarily sorted. Recurse to resort and resimplify
668 // any operands we just aquired.
669 if (DeletedAdd)
670 return get(Ops);
671 }
672
673 // Skip over the add expression until we get to a multiply.
674 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
675 ++Idx;
676
677 // If we are adding something to a multiply expression, make sure the
678 // something is not already an operand of the multiply. If so, merge it into
679 // the multiply.
680 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
681 SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
682 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
683 SCEV *MulOpSCEV = Mul->getOperand(MulOp);
684 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
Chris Lattner6a1a78a2004-12-04 20:54:32 +0000685 if (MulOpSCEV == Ops[AddOp] && !isa<SCEVConstant>(MulOpSCEV)) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000686 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
687 SCEVHandle InnerMul = Mul->getOperand(MulOp == 0);
688 if (Mul->getNumOperands() != 2) {
689 // If the multiply has more than two operands, we must get the
690 // Y*Z term.
691 std::vector<SCEVHandle> MulOps(Mul->op_begin(), Mul->op_end());
692 MulOps.erase(MulOps.begin()+MulOp);
693 InnerMul = SCEVMulExpr::get(MulOps);
694 }
Chris Lattnerb06432c2004-04-23 21:29:03 +0000695 SCEVHandle One = SCEVUnknown::getIntegerSCEV(1, Ty);
Chris Lattner53e677a2004-04-02 20:23:17 +0000696 SCEVHandle AddOne = SCEVAddExpr::get(InnerMul, One);
697 SCEVHandle OuterMul = SCEVMulExpr::get(AddOne, Ops[AddOp]);
698 if (Ops.size() == 2) return OuterMul;
699 if (AddOp < Idx) {
700 Ops.erase(Ops.begin()+AddOp);
701 Ops.erase(Ops.begin()+Idx-1);
702 } else {
703 Ops.erase(Ops.begin()+Idx);
704 Ops.erase(Ops.begin()+AddOp-1);
705 }
706 Ops.push_back(OuterMul);
707 return SCEVAddExpr::get(Ops);
708 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000709
Chris Lattner53e677a2004-04-02 20:23:17 +0000710 // Check this multiply against other multiplies being added together.
711 for (unsigned OtherMulIdx = Idx+1;
712 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
713 ++OtherMulIdx) {
714 SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
715 // If MulOp occurs in OtherMul, we can fold the two multiplies
716 // together.
717 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
718 OMulOp != e; ++OMulOp)
719 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
720 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
721 SCEVHandle InnerMul1 = Mul->getOperand(MulOp == 0);
722 if (Mul->getNumOperands() != 2) {
723 std::vector<SCEVHandle> MulOps(Mul->op_begin(), Mul->op_end());
724 MulOps.erase(MulOps.begin()+MulOp);
725 InnerMul1 = SCEVMulExpr::get(MulOps);
726 }
727 SCEVHandle InnerMul2 = OtherMul->getOperand(OMulOp == 0);
728 if (OtherMul->getNumOperands() != 2) {
729 std::vector<SCEVHandle> MulOps(OtherMul->op_begin(),
730 OtherMul->op_end());
731 MulOps.erase(MulOps.begin()+OMulOp);
732 InnerMul2 = SCEVMulExpr::get(MulOps);
733 }
734 SCEVHandle InnerMulSum = SCEVAddExpr::get(InnerMul1,InnerMul2);
735 SCEVHandle OuterMul = SCEVMulExpr::get(MulOpSCEV, InnerMulSum);
736 if (Ops.size() == 2) return OuterMul;
737 Ops.erase(Ops.begin()+Idx);
738 Ops.erase(Ops.begin()+OtherMulIdx-1);
739 Ops.push_back(OuterMul);
740 return SCEVAddExpr::get(Ops);
741 }
742 }
743 }
744 }
745
746 // If there are any add recurrences in the operands list, see if any other
747 // added values are loop invariant. If so, we can fold them into the
748 // recurrence.
749 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
750 ++Idx;
751
752 // Scan over all recurrences, trying to fold loop invariants into them.
753 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
754 // Scan all of the other operands to this add and add them to the vector if
755 // they are loop invariant w.r.t. the recurrence.
756 std::vector<SCEVHandle> LIOps;
757 SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
758 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
759 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
760 LIOps.push_back(Ops[i]);
761 Ops.erase(Ops.begin()+i);
762 --i; --e;
763 }
764
765 // If we found some loop invariants, fold them into the recurrence.
766 if (!LIOps.empty()) {
767 // NLI + LI + { Start,+,Step} --> NLI + { LI+Start,+,Step }
768 LIOps.push_back(AddRec->getStart());
769
770 std::vector<SCEVHandle> AddRecOps(AddRec->op_begin(), AddRec->op_end());
771 AddRecOps[0] = SCEVAddExpr::get(LIOps);
772
773 SCEVHandle NewRec = SCEVAddRecExpr::get(AddRecOps, AddRec->getLoop());
774 // If all of the other operands were loop invariant, we are done.
775 if (Ops.size() == 1) return NewRec;
776
777 // Otherwise, add the folded AddRec by the non-liv parts.
778 for (unsigned i = 0;; ++i)
779 if (Ops[i] == AddRec) {
780 Ops[i] = NewRec;
781 break;
782 }
783 return SCEVAddExpr::get(Ops);
784 }
785
786 // Okay, if there weren't any loop invariants to be folded, check to see if
787 // there are multiple AddRec's with the same loop induction variable being
788 // added together. If so, we can fold them.
789 for (unsigned OtherIdx = Idx+1;
790 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
791 if (OtherIdx != Idx) {
792 SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
793 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
794 // Other + {A,+,B} + {C,+,D} --> Other + {A+C,+,B+D}
795 std::vector<SCEVHandle> NewOps(AddRec->op_begin(), AddRec->op_end());
796 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); i != e; ++i) {
797 if (i >= NewOps.size()) {
798 NewOps.insert(NewOps.end(), OtherAddRec->op_begin()+i,
799 OtherAddRec->op_end());
800 break;
801 }
802 NewOps[i] = SCEVAddExpr::get(NewOps[i], OtherAddRec->getOperand(i));
803 }
804 SCEVHandle NewAddRec = SCEVAddRecExpr::get(NewOps, AddRec->getLoop());
805
806 if (Ops.size() == 2) return NewAddRec;
807
808 Ops.erase(Ops.begin()+Idx);
809 Ops.erase(Ops.begin()+OtherIdx-1);
810 Ops.push_back(NewAddRec);
811 return SCEVAddExpr::get(Ops);
812 }
813 }
814
815 // Otherwise couldn't fold anything into this recurrence. Move onto the
816 // next one.
817 }
818
819 // Okay, it looks like we really DO need an add expr. Check to see if we
820 // already have one, otherwise create a new one.
821 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
Chris Lattnerb3364092006-10-04 21:49:37 +0000822 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scAddExpr,
823 SCEVOps)];
Chris Lattner53e677a2004-04-02 20:23:17 +0000824 if (Result == 0) Result = new SCEVAddExpr(Ops);
825 return Result;
826}
827
828
829SCEVHandle SCEVMulExpr::get(std::vector<SCEVHandle> &Ops) {
830 assert(!Ops.empty() && "Cannot get empty mul!");
831
832 // Sort by complexity, this groups all similar expression types together.
Chris Lattner8d741b82004-06-20 06:23:15 +0000833 GroupByComplexity(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +0000834
835 // If there are any constants, fold them together.
836 unsigned Idx = 0;
837 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
838
839 // C1*(C2+V) -> C1*C2 + C1*V
840 if (Ops.size() == 2)
841 if (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
842 if (Add->getNumOperands() == 2 &&
843 isa<SCEVConstant>(Add->getOperand(0)))
844 return SCEVAddExpr::get(SCEVMulExpr::get(LHSC, Add->getOperand(0)),
845 SCEVMulExpr::get(LHSC, Add->getOperand(1)));
846
847
848 ++Idx;
849 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
850 // We found two constants, fold them together!
851 Constant *Fold = ConstantExpr::getMul(LHSC->getValue(), RHSC->getValue());
852 if (ConstantInt *CI = dyn_cast<ConstantInt>(Fold)) {
853 Ops[0] = SCEVConstant::get(CI);
854 Ops.erase(Ops.begin()+1); // Erase the folded element
855 if (Ops.size() == 1) return Ops[0];
Chris Lattner7ffc07d2005-02-26 18:50:19 +0000856 LHSC = cast<SCEVConstant>(Ops[0]);
Chris Lattner53e677a2004-04-02 20:23:17 +0000857 } else {
858 // If we couldn't fold the expression, move to the next constant. Note
859 // that this is impossible to happen in practice because we always
860 // constant fold constant ints to constant ints.
861 ++Idx;
862 }
863 }
864
865 // If we are left with a constant one being multiplied, strip it off.
866 if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) {
867 Ops.erase(Ops.begin());
868 --Idx;
869 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isNullValue()) {
870 // If we have a multiply of zero, it will always be zero.
871 return Ops[0];
872 }
873 }
874
875 // Skip over the add expression until we get to a multiply.
876 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
877 ++Idx;
878
879 if (Ops.size() == 1)
880 return Ops[0];
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000881
Chris Lattner53e677a2004-04-02 20:23:17 +0000882 // If there are mul operands inline them all into this expression.
883 if (Idx < Ops.size()) {
884 bool DeletedMul = false;
885 while (SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
886 // If we have an mul, expand the mul operands onto the end of the operands
887 // list.
888 Ops.insert(Ops.end(), Mul->op_begin(), Mul->op_end());
889 Ops.erase(Ops.begin()+Idx);
890 DeletedMul = true;
891 }
892
893 // If we deleted at least one mul, we added operands to the end of the list,
894 // and they are not necessarily sorted. Recurse to resort and resimplify
895 // any operands we just aquired.
896 if (DeletedMul)
897 return get(Ops);
898 }
899
900 // If there are any add recurrences in the operands list, see if any other
901 // added values are loop invariant. If so, we can fold them into the
902 // recurrence.
903 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
904 ++Idx;
905
906 // Scan over all recurrences, trying to fold loop invariants into them.
907 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
908 // Scan all of the other operands to this mul and add them to the vector if
909 // they are loop invariant w.r.t. the recurrence.
910 std::vector<SCEVHandle> LIOps;
911 SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
912 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
913 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
914 LIOps.push_back(Ops[i]);
915 Ops.erase(Ops.begin()+i);
916 --i; --e;
917 }
918
919 // If we found some loop invariants, fold them into the recurrence.
920 if (!LIOps.empty()) {
921 // NLI * LI * { Start,+,Step} --> NLI * { LI*Start,+,LI*Step }
922 std::vector<SCEVHandle> NewOps;
923 NewOps.reserve(AddRec->getNumOperands());
924 if (LIOps.size() == 1) {
925 SCEV *Scale = LIOps[0];
926 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
927 NewOps.push_back(SCEVMulExpr::get(Scale, AddRec->getOperand(i)));
928 } else {
929 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
930 std::vector<SCEVHandle> MulOps(LIOps);
931 MulOps.push_back(AddRec->getOperand(i));
932 NewOps.push_back(SCEVMulExpr::get(MulOps));
933 }
934 }
935
936 SCEVHandle NewRec = SCEVAddRecExpr::get(NewOps, AddRec->getLoop());
937
938 // If all of the other operands were loop invariant, we are done.
939 if (Ops.size() == 1) return NewRec;
940
941 // Otherwise, multiply the folded AddRec by the non-liv parts.
942 for (unsigned i = 0;; ++i)
943 if (Ops[i] == AddRec) {
944 Ops[i] = NewRec;
945 break;
946 }
947 return SCEVMulExpr::get(Ops);
948 }
949
950 // Okay, if there weren't any loop invariants to be folded, check to see if
951 // there are multiple AddRec's with the same loop induction variable being
952 // multiplied together. If so, we can fold them.
953 for (unsigned OtherIdx = Idx+1;
954 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
955 if (OtherIdx != Idx) {
956 SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
957 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
958 // F * G --> {A,+,B} * {C,+,D} --> {A*C,+,F*D + G*B + B*D}
959 SCEVAddRecExpr *F = AddRec, *G = OtherAddRec;
960 SCEVHandle NewStart = SCEVMulExpr::get(F->getStart(),
961 G->getStart());
962 SCEVHandle B = F->getStepRecurrence();
963 SCEVHandle D = G->getStepRecurrence();
964 SCEVHandle NewStep = SCEVAddExpr::get(SCEVMulExpr::get(F, D),
965 SCEVMulExpr::get(G, B),
966 SCEVMulExpr::get(B, D));
967 SCEVHandle NewAddRec = SCEVAddRecExpr::get(NewStart, NewStep,
968 F->getLoop());
969 if (Ops.size() == 2) return NewAddRec;
970
971 Ops.erase(Ops.begin()+Idx);
972 Ops.erase(Ops.begin()+OtherIdx-1);
973 Ops.push_back(NewAddRec);
974 return SCEVMulExpr::get(Ops);
975 }
976 }
977
978 // Otherwise couldn't fold anything into this recurrence. Move onto the
979 // next one.
980 }
981
982 // Okay, it looks like we really DO need an mul expr. Check to see if we
983 // already have one, otherwise create a new one.
984 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
Chris Lattnerb3364092006-10-04 21:49:37 +0000985 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scMulExpr,
986 SCEVOps)];
Chris Lattner6a1a78a2004-12-04 20:54:32 +0000987 if (Result == 0)
988 Result = new SCEVMulExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +0000989 return Result;
990}
991
Chris Lattner60a05cc2006-04-01 04:48:52 +0000992SCEVHandle SCEVSDivExpr::get(const SCEVHandle &LHS, const SCEVHandle &RHS) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000993 if (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
994 if (RHSC->getValue()->equalsInt(1))
Reid Spencer1628cec2006-10-26 06:15:43 +0000995 return LHS; // X sdiv 1 --> x
Chris Lattner53e677a2004-04-02 20:23:17 +0000996 if (RHSC->getValue()->isAllOnesValue())
Reid Spencer1628cec2006-10-26 06:15:43 +0000997 return SCEV::getNegativeSCEV(LHS); // X sdiv -1 --> -x
Chris Lattner53e677a2004-04-02 20:23:17 +0000998
999 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
1000 Constant *LHSCV = LHSC->getValue();
1001 Constant *RHSCV = RHSC->getValue();
Chris Lattner60a05cc2006-04-01 04:48:52 +00001002 if (LHSCV->getType()->isUnsigned())
Reid Spencer7858b332006-12-05 19:14:13 +00001003 LHSCV = ConstantExpr::getBitCast(LHSCV,
1004 LHSCV->getType()->getSignedVersion());
Chris Lattner60a05cc2006-04-01 04:48:52 +00001005 if (RHSCV->getType()->isUnsigned())
Reid Spencer7858b332006-12-05 19:14:13 +00001006 RHSCV = ConstantExpr::getBitCast(RHSCV, LHSCV->getType());
Reid Spencer1628cec2006-10-26 06:15:43 +00001007 return SCEVUnknown::get(ConstantExpr::getSDiv(LHSCV, RHSCV));
Chris Lattner53e677a2004-04-02 20:23:17 +00001008 }
1009 }
1010
1011 // FIXME: implement folding of (X*4)/4 when we know X*4 doesn't overflow.
1012
Chris Lattnerb3364092006-10-04 21:49:37 +00001013 SCEVSDivExpr *&Result = (*SCEVSDivs)[std::make_pair(LHS, RHS)];
Chris Lattner60a05cc2006-04-01 04:48:52 +00001014 if (Result == 0) Result = new SCEVSDivExpr(LHS, RHS);
Chris Lattner53e677a2004-04-02 20:23:17 +00001015 return Result;
1016}
1017
1018
1019/// SCEVAddRecExpr::get - Get a add recurrence expression for the
1020/// specified loop. Simplify the expression as much as possible.
1021SCEVHandle SCEVAddRecExpr::get(const SCEVHandle &Start,
1022 const SCEVHandle &Step, const Loop *L) {
1023 std::vector<SCEVHandle> Operands;
1024 Operands.push_back(Start);
1025 if (SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
1026 if (StepChrec->getLoop() == L) {
1027 Operands.insert(Operands.end(), StepChrec->op_begin(),
1028 StepChrec->op_end());
1029 return get(Operands, L);
1030 }
1031
1032 Operands.push_back(Step);
1033 return get(Operands, L);
1034}
1035
1036/// SCEVAddRecExpr::get - Get a add recurrence expression for the
1037/// specified loop. Simplify the expression as much as possible.
1038SCEVHandle SCEVAddRecExpr::get(std::vector<SCEVHandle> &Operands,
1039 const Loop *L) {
1040 if (Operands.size() == 1) return Operands[0];
1041
1042 if (SCEVConstant *StepC = dyn_cast<SCEVConstant>(Operands.back()))
1043 if (StepC->getValue()->isNullValue()) {
1044 Operands.pop_back();
1045 return get(Operands, L); // { X,+,0 } --> X
1046 }
1047
1048 SCEVAddRecExpr *&Result =
Chris Lattnerb3364092006-10-04 21:49:37 +00001049 (*SCEVAddRecExprs)[std::make_pair(L, std::vector<SCEV*>(Operands.begin(),
1050 Operands.end()))];
Chris Lattner53e677a2004-04-02 20:23:17 +00001051 if (Result == 0) Result = new SCEVAddRecExpr(Operands, L);
1052 return Result;
1053}
1054
Chris Lattner0a7f98c2004-04-15 15:07:24 +00001055SCEVHandle SCEVUnknown::get(Value *V) {
1056 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
1057 return SCEVConstant::get(CI);
Chris Lattnerb3364092006-10-04 21:49:37 +00001058 SCEVUnknown *&Result = (*SCEVUnknowns)[V];
Chris Lattner0a7f98c2004-04-15 15:07:24 +00001059 if (Result == 0) Result = new SCEVUnknown(V);
1060 return Result;
1061}
1062
Chris Lattner53e677a2004-04-02 20:23:17 +00001063
1064//===----------------------------------------------------------------------===//
Chris Lattner53e677a2004-04-02 20:23:17 +00001065// ScalarEvolutionsImpl Definition and Implementation
1066//===----------------------------------------------------------------------===//
1067//
1068/// ScalarEvolutionsImpl - This class implements the main driver for the scalar
1069/// evolution code.
1070///
1071namespace {
Chris Lattner95255282006-06-28 23:17:24 +00001072 struct VISIBILITY_HIDDEN ScalarEvolutionsImpl {
Chris Lattner53e677a2004-04-02 20:23:17 +00001073 /// F - The function we are analyzing.
1074 ///
1075 Function &F;
1076
1077 /// LI - The loop information for the function we are currently analyzing.
1078 ///
1079 LoopInfo &LI;
1080
1081 /// UnknownValue - This SCEV is used to represent unknown trip counts and
1082 /// things.
1083 SCEVHandle UnknownValue;
1084
1085 /// Scalars - This is a cache of the scalars we have analyzed so far.
1086 ///
1087 std::map<Value*, SCEVHandle> Scalars;
1088
1089 /// IterationCounts - Cache the iteration count of the loops for this
1090 /// function as they are computed.
1091 std::map<const Loop*, SCEVHandle> IterationCounts;
1092
Chris Lattner3221ad02004-04-17 22:58:41 +00001093 /// ConstantEvolutionLoopExitValue - This map contains entries for all of
1094 /// the PHI instructions that we attempt to compute constant evolutions for.
1095 /// This allows us to avoid potentially expensive recomputation of these
1096 /// properties. An instruction maps to null if we are unable to compute its
1097 /// exit value.
1098 std::map<PHINode*, Constant*> ConstantEvolutionLoopExitValue;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001099
Chris Lattner53e677a2004-04-02 20:23:17 +00001100 public:
1101 ScalarEvolutionsImpl(Function &f, LoopInfo &li)
1102 : F(f), LI(li), UnknownValue(new SCEVCouldNotCompute()) {}
1103
1104 /// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
1105 /// expression and create a new one.
1106 SCEVHandle getSCEV(Value *V);
1107
Chris Lattnera0740fb2005-08-09 23:36:33 +00001108 /// hasSCEV - Return true if the SCEV for this value has already been
1109 /// computed.
1110 bool hasSCEV(Value *V) const {
1111 return Scalars.count(V);
1112 }
1113
1114 /// setSCEV - Insert the specified SCEV into the map of current SCEVs for
1115 /// the specified value.
1116 void setSCEV(Value *V, const SCEVHandle &H) {
1117 bool isNew = Scalars.insert(std::make_pair(V, H)).second;
1118 assert(isNew && "This entry already existed!");
1119 }
1120
1121
Chris Lattner53e677a2004-04-02 20:23:17 +00001122 /// getSCEVAtScope - Compute the value of the specified expression within
1123 /// the indicated loop (which may be null to indicate in no loop). If the
1124 /// expression cannot be evaluated, return UnknownValue itself.
1125 SCEVHandle getSCEVAtScope(SCEV *V, const Loop *L);
1126
1127
1128 /// hasLoopInvariantIterationCount - Return true if the specified loop has
1129 /// an analyzable loop-invariant iteration count.
1130 bool hasLoopInvariantIterationCount(const Loop *L);
1131
1132 /// getIterationCount - If the specified loop has a predictable iteration
1133 /// count, return it. Note that it is not valid to call this method on a
1134 /// loop without a loop-invariant iteration count.
1135 SCEVHandle getIterationCount(const Loop *L);
1136
1137 /// deleteInstructionFromRecords - This method should be called by the
1138 /// client before it removes an instruction from the program, to make sure
1139 /// that no dangling references are left around.
1140 void deleteInstructionFromRecords(Instruction *I);
1141
1142 private:
1143 /// createSCEV - We know that there is no SCEV for the specified value.
1144 /// Analyze the expression.
1145 SCEVHandle createSCEV(Value *V);
Chris Lattner53e677a2004-04-02 20:23:17 +00001146
1147 /// createNodeForPHI - Provide the special handling we need to analyze PHI
1148 /// SCEVs.
1149 SCEVHandle createNodeForPHI(PHINode *PN);
Chris Lattner4dc534c2005-02-13 04:37:18 +00001150
1151 /// ReplaceSymbolicValueWithConcrete - This looks up the computed SCEV value
1152 /// for the specified instruction and replaces any references to the
1153 /// symbolic value SymName with the specified value. This is used during
1154 /// PHI resolution.
1155 void ReplaceSymbolicValueWithConcrete(Instruction *I,
1156 const SCEVHandle &SymName,
1157 const SCEVHandle &NewVal);
Chris Lattner53e677a2004-04-02 20:23:17 +00001158
1159 /// ComputeIterationCount - Compute the number of times the specified loop
1160 /// will iterate.
1161 SCEVHandle ComputeIterationCount(const Loop *L);
1162
Chris Lattner673e02b2004-10-12 01:49:27 +00001163 /// ComputeLoadConstantCompareIterationCount - Given an exit condition of
1164 /// 'setcc load X, cst', try to se if we can compute the trip count.
1165 SCEVHandle ComputeLoadConstantCompareIterationCount(LoadInst *LI,
1166 Constant *RHS,
1167 const Loop *L,
1168 unsigned SetCCOpcode);
1169
Chris Lattner7980fb92004-04-17 18:36:24 +00001170 /// ComputeIterationCountExhaustively - If the trip is known to execute a
1171 /// constant number of times (the condition evolves only from constants),
1172 /// try to evaluate a few iterations of the loop until we get the exit
1173 /// condition gets a value of ExitWhen (true or false). If we cannot
1174 /// evaluate the trip count of the loop, return UnknownValue.
1175 SCEVHandle ComputeIterationCountExhaustively(const Loop *L, Value *Cond,
1176 bool ExitWhen);
1177
Chris Lattner53e677a2004-04-02 20:23:17 +00001178 /// HowFarToZero - Return the number of times a backedge comparing the
1179 /// specified value to zero will execute. If not computable, return
Chris Lattnerdb25de42005-08-15 23:33:51 +00001180 /// UnknownValue.
Chris Lattner53e677a2004-04-02 20:23:17 +00001181 SCEVHandle HowFarToZero(SCEV *V, const Loop *L);
1182
1183 /// HowFarToNonZero - Return the number of times a backedge checking the
1184 /// specified value for nonzero will execute. If not computable, return
Chris Lattnerdb25de42005-08-15 23:33:51 +00001185 /// UnknownValue.
Chris Lattner53e677a2004-04-02 20:23:17 +00001186 SCEVHandle HowFarToNonZero(SCEV *V, const Loop *L);
Chris Lattner3221ad02004-04-17 22:58:41 +00001187
Chris Lattnerdb25de42005-08-15 23:33:51 +00001188 /// HowManyLessThans - Return the number of times a backedge containing the
1189 /// specified less-than comparison will execute. If not computable, return
1190 /// UnknownValue.
1191 SCEVHandle HowManyLessThans(SCEV *LHS, SCEV *RHS, const Loop *L);
1192
Chris Lattner3221ad02004-04-17 22:58:41 +00001193 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
1194 /// in the header of its containing loop, we know the loop executes a
1195 /// constant number of times, and the PHI node is just a recurrence
1196 /// involving constants, fold it.
1197 Constant *getConstantEvolutionLoopExitValue(PHINode *PN, uint64_t Its,
1198 const Loop *L);
Chris Lattner53e677a2004-04-02 20:23:17 +00001199 };
1200}
1201
1202//===----------------------------------------------------------------------===//
1203// Basic SCEV Analysis and PHI Idiom Recognition Code
1204//
1205
1206/// deleteInstructionFromRecords - This method should be called by the
1207/// client before it removes an instruction from the program, to make sure
1208/// that no dangling references are left around.
1209void ScalarEvolutionsImpl::deleteInstructionFromRecords(Instruction *I) {
1210 Scalars.erase(I);
Chris Lattner3221ad02004-04-17 22:58:41 +00001211 if (PHINode *PN = dyn_cast<PHINode>(I))
1212 ConstantEvolutionLoopExitValue.erase(PN);
Chris Lattner53e677a2004-04-02 20:23:17 +00001213}
1214
1215
1216/// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
1217/// expression and create a new one.
1218SCEVHandle ScalarEvolutionsImpl::getSCEV(Value *V) {
1219 assert(V->getType() != Type::VoidTy && "Can't analyze void expressions!");
1220
1221 std::map<Value*, SCEVHandle>::iterator I = Scalars.find(V);
1222 if (I != Scalars.end()) return I->second;
1223 SCEVHandle S = createSCEV(V);
1224 Scalars.insert(std::make_pair(V, S));
1225 return S;
1226}
1227
Chris Lattner4dc534c2005-02-13 04:37:18 +00001228/// ReplaceSymbolicValueWithConcrete - This looks up the computed SCEV value for
1229/// the specified instruction and replaces any references to the symbolic value
1230/// SymName with the specified value. This is used during PHI resolution.
1231void ScalarEvolutionsImpl::
1232ReplaceSymbolicValueWithConcrete(Instruction *I, const SCEVHandle &SymName,
1233 const SCEVHandle &NewVal) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001234 std::map<Value*, SCEVHandle>::iterator SI = Scalars.find(I);
Chris Lattner4dc534c2005-02-13 04:37:18 +00001235 if (SI == Scalars.end()) return;
Chris Lattner53e677a2004-04-02 20:23:17 +00001236
Chris Lattner4dc534c2005-02-13 04:37:18 +00001237 SCEVHandle NV =
1238 SI->second->replaceSymbolicValuesWithConcrete(SymName, NewVal);
1239 if (NV == SI->second) return; // No change.
1240
1241 SI->second = NV; // Update the scalars map!
1242
1243 // Any instruction values that use this instruction might also need to be
1244 // updated!
1245 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1246 UI != E; ++UI)
1247 ReplaceSymbolicValueWithConcrete(cast<Instruction>(*UI), SymName, NewVal);
1248}
Chris Lattner53e677a2004-04-02 20:23:17 +00001249
1250/// createNodeForPHI - PHI nodes have two cases. Either the PHI node exists in
1251/// a loop header, making it a potential recurrence, or it doesn't.
1252///
1253SCEVHandle ScalarEvolutionsImpl::createNodeForPHI(PHINode *PN) {
1254 if (PN->getNumIncomingValues() == 2) // The loops have been canonicalized.
1255 if (const Loop *L = LI.getLoopFor(PN->getParent()))
1256 if (L->getHeader() == PN->getParent()) {
1257 // If it lives in the loop header, it has two incoming values, one
1258 // from outside the loop, and one from inside.
1259 unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0));
1260 unsigned BackEdge = IncomingEdge^1;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001261
Chris Lattner53e677a2004-04-02 20:23:17 +00001262 // While we are analyzing this PHI node, handle its value symbolically.
1263 SCEVHandle SymbolicName = SCEVUnknown::get(PN);
1264 assert(Scalars.find(PN) == Scalars.end() &&
1265 "PHI node already processed?");
1266 Scalars.insert(std::make_pair(PN, SymbolicName));
1267
1268 // Using this symbolic name for the PHI, analyze the value coming around
1269 // the back-edge.
1270 SCEVHandle BEValue = getSCEV(PN->getIncomingValue(BackEdge));
1271
1272 // NOTE: If BEValue is loop invariant, we know that the PHI node just
1273 // has a special value for the first iteration of the loop.
1274
1275 // If the value coming around the backedge is an add with the symbolic
1276 // value we just inserted, then we found a simple induction variable!
1277 if (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
1278 // If there is a single occurrence of the symbolic value, replace it
1279 // with a recurrence.
1280 unsigned FoundIndex = Add->getNumOperands();
1281 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
1282 if (Add->getOperand(i) == SymbolicName)
1283 if (FoundIndex == e) {
1284 FoundIndex = i;
1285 break;
1286 }
1287
1288 if (FoundIndex != Add->getNumOperands()) {
1289 // Create an add with everything but the specified operand.
1290 std::vector<SCEVHandle> Ops;
1291 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
1292 if (i != FoundIndex)
1293 Ops.push_back(Add->getOperand(i));
1294 SCEVHandle Accum = SCEVAddExpr::get(Ops);
1295
1296 // This is not a valid addrec if the step amount is varying each
1297 // loop iteration, but is not itself an addrec in this loop.
1298 if (Accum->isLoopInvariant(L) ||
1299 (isa<SCEVAddRecExpr>(Accum) &&
1300 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
1301 SCEVHandle StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
1302 SCEVHandle PHISCEV = SCEVAddRecExpr::get(StartVal, Accum, L);
1303
1304 // Okay, for the entire analysis of this edge we assumed the PHI
1305 // to be symbolic. We now need to go back and update all of the
1306 // entries for the scalars that use the PHI (except for the PHI
1307 // itself) to use the new analyzed value instead of the "symbolic"
1308 // value.
Chris Lattner4dc534c2005-02-13 04:37:18 +00001309 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
Chris Lattner53e677a2004-04-02 20:23:17 +00001310 return PHISCEV;
1311 }
1312 }
Chris Lattner97156e72006-04-26 18:34:07 +00001313 } else if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(BEValue)) {
1314 // Otherwise, this could be a loop like this:
1315 // i = 0; for (j = 1; ..; ++j) { .... i = j; }
1316 // In this case, j = {1,+,1} and BEValue is j.
1317 // Because the other in-value of i (0) fits the evolution of BEValue
1318 // i really is an addrec evolution.
1319 if (AddRec->getLoop() == L && AddRec->isAffine()) {
1320 SCEVHandle StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
1321
1322 // If StartVal = j.start - j.stride, we can use StartVal as the
1323 // initial step of the addrec evolution.
1324 if (StartVal == SCEV::getMinusSCEV(AddRec->getOperand(0),
1325 AddRec->getOperand(1))) {
1326 SCEVHandle PHISCEV =
1327 SCEVAddRecExpr::get(StartVal, AddRec->getOperand(1), L);
1328
1329 // Okay, for the entire analysis of this edge we assumed the PHI
1330 // to be symbolic. We now need to go back and update all of the
1331 // entries for the scalars that use the PHI (except for the PHI
1332 // itself) to use the new analyzed value instead of the "symbolic"
1333 // value.
1334 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
1335 return PHISCEV;
1336 }
1337 }
Chris Lattner53e677a2004-04-02 20:23:17 +00001338 }
1339
1340 return SymbolicName;
1341 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001342
Chris Lattner53e677a2004-04-02 20:23:17 +00001343 // If it's not a loop phi, we can't handle it yet.
1344 return SCEVUnknown::get(PN);
1345}
1346
Chris Lattner53e677a2004-04-02 20:23:17 +00001347
1348/// createSCEV - We know that there is no SCEV for the specified value.
1349/// Analyze the expression.
1350///
1351SCEVHandle ScalarEvolutionsImpl::createSCEV(Value *V) {
1352 if (Instruction *I = dyn_cast<Instruction>(V)) {
1353 switch (I->getOpcode()) {
1354 case Instruction::Add:
1355 return SCEVAddExpr::get(getSCEV(I->getOperand(0)),
1356 getSCEV(I->getOperand(1)));
1357 case Instruction::Mul:
1358 return SCEVMulExpr::get(getSCEV(I->getOperand(0)),
1359 getSCEV(I->getOperand(1)));
Reid Spencer1628cec2006-10-26 06:15:43 +00001360 case Instruction::SDiv:
1361 return SCEVSDivExpr::get(getSCEV(I->getOperand(0)),
1362 getSCEV(I->getOperand(1)));
Chris Lattner53e677a2004-04-02 20:23:17 +00001363 break;
1364
1365 case Instruction::Sub:
Chris Lattnerbac5b462005-03-09 05:34:41 +00001366 return SCEV::getMinusSCEV(getSCEV(I->getOperand(0)),
1367 getSCEV(I->getOperand(1)));
Chris Lattner53e677a2004-04-02 20:23:17 +00001368
1369 case Instruction::Shl:
1370 // Turn shift left of a constant amount into a multiply.
1371 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1372 Constant *X = ConstantInt::get(V->getType(), 1);
1373 X = ConstantExpr::getShl(X, SA);
1374 return SCEVMulExpr::get(getSCEV(I->getOperand(0)), getSCEV(X));
1375 }
1376 break;
1377
Reid Spencer3da59db2006-11-27 01:05:10 +00001378 case Instruction::Trunc:
1379 if (I->getType()->isInteger() && I->getOperand(0)->getType()->isInteger())
1380 return SCEVTruncateExpr::get(getSCEV(I->getOperand(0)),
1381 I->getType()->getUnsignedVersion());
1382 break;
1383
1384 case Instruction::ZExt:
1385 if (I->getType()->isInteger() && I->getOperand(0)->getType()->isInteger())
1386 return SCEVZeroExtendExpr::get(getSCEV(I->getOperand(0)),
1387 I->getType()->getUnsignedVersion());
1388 break;
1389
1390 case Instruction::BitCast:
1391 // BitCasts are no-op casts so we just eliminate the cast.
1392 return getSCEV(I->getOperand(0));
Chris Lattner53e677a2004-04-02 20:23:17 +00001393
1394 case Instruction::PHI:
1395 return createNodeForPHI(cast<PHINode>(I));
1396
1397 default: // We cannot analyze this expression.
1398 break;
1399 }
1400 }
1401
1402 return SCEVUnknown::get(V);
1403}
1404
1405
1406
1407//===----------------------------------------------------------------------===//
1408// Iteration Count Computation Code
1409//
1410
1411/// getIterationCount - If the specified loop has a predictable iteration
1412/// count, return it. Note that it is not valid to call this method on a
1413/// loop without a loop-invariant iteration count.
1414SCEVHandle ScalarEvolutionsImpl::getIterationCount(const Loop *L) {
1415 std::map<const Loop*, SCEVHandle>::iterator I = IterationCounts.find(L);
1416 if (I == IterationCounts.end()) {
1417 SCEVHandle ItCount = ComputeIterationCount(L);
1418 I = IterationCounts.insert(std::make_pair(L, ItCount)).first;
1419 if (ItCount != UnknownValue) {
1420 assert(ItCount->isLoopInvariant(L) &&
1421 "Computed trip count isn't loop invariant for loop!");
1422 ++NumTripCountsComputed;
1423 } else if (isa<PHINode>(L->getHeader()->begin())) {
1424 // Only count loops that have phi nodes as not being computable.
1425 ++NumTripCountsNotComputed;
1426 }
1427 }
1428 return I->second;
1429}
1430
1431/// ComputeIterationCount - Compute the number of times the specified loop
1432/// will iterate.
1433SCEVHandle ScalarEvolutionsImpl::ComputeIterationCount(const Loop *L) {
1434 // If the loop has a non-one exit block count, we can't analyze it.
Chris Lattnerf1ab4b42004-04-18 22:14:10 +00001435 std::vector<BasicBlock*> ExitBlocks;
1436 L->getExitBlocks(ExitBlocks);
1437 if (ExitBlocks.size() != 1) return UnknownValue;
Chris Lattner53e677a2004-04-02 20:23:17 +00001438
1439 // Okay, there is one exit block. Try to find the condition that causes the
1440 // loop to be exited.
Chris Lattnerf1ab4b42004-04-18 22:14:10 +00001441 BasicBlock *ExitBlock = ExitBlocks[0];
Chris Lattner53e677a2004-04-02 20:23:17 +00001442
1443 BasicBlock *ExitingBlock = 0;
1444 for (pred_iterator PI = pred_begin(ExitBlock), E = pred_end(ExitBlock);
1445 PI != E; ++PI)
1446 if (L->contains(*PI)) {
1447 if (ExitingBlock == 0)
1448 ExitingBlock = *PI;
1449 else
1450 return UnknownValue; // More than one block exiting!
1451 }
1452 assert(ExitingBlock && "No exits from loop, something is broken!");
1453
1454 // Okay, we've computed the exiting block. See what condition causes us to
1455 // exit.
1456 //
1457 // FIXME: we should be able to handle switch instructions (with a single exit)
1458 // FIXME: We should handle cast of int to bool as well
1459 BranchInst *ExitBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
1460 if (ExitBr == 0) return UnknownValue;
1461 assert(ExitBr->isConditional() && "If unconditional, it can't be in loop!");
1462 SetCondInst *ExitCond = dyn_cast<SetCondInst>(ExitBr->getCondition());
Chris Lattner7980fb92004-04-17 18:36:24 +00001463 if (ExitCond == 0) // Not a setcc
1464 return ComputeIterationCountExhaustively(L, ExitBr->getCondition(),
1465 ExitBr->getSuccessor(0) == ExitBlock);
Chris Lattner53e677a2004-04-02 20:23:17 +00001466
Chris Lattner673e02b2004-10-12 01:49:27 +00001467 // If the condition was exit on true, convert the condition to exit on false.
1468 Instruction::BinaryOps Cond;
1469 if (ExitBr->getSuccessor(1) == ExitBlock)
1470 Cond = ExitCond->getOpcode();
1471 else
1472 Cond = ExitCond->getInverseCondition();
1473
1474 // Handle common loops like: for (X = "string"; *X; ++X)
1475 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
1476 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
1477 SCEVHandle ItCnt =
1478 ComputeLoadConstantCompareIterationCount(LI, RHS, L, Cond);
1479 if (!isa<SCEVCouldNotCompute>(ItCnt)) return ItCnt;
1480 }
1481
Chris Lattner53e677a2004-04-02 20:23:17 +00001482 SCEVHandle LHS = getSCEV(ExitCond->getOperand(0));
1483 SCEVHandle RHS = getSCEV(ExitCond->getOperand(1));
1484
1485 // Try to evaluate any dependencies out of the loop.
1486 SCEVHandle Tmp = getSCEVAtScope(LHS, L);
1487 if (!isa<SCEVCouldNotCompute>(Tmp)) LHS = Tmp;
1488 Tmp = getSCEVAtScope(RHS, L);
1489 if (!isa<SCEVCouldNotCompute>(Tmp)) RHS = Tmp;
1490
Chris Lattner53e677a2004-04-02 20:23:17 +00001491 // At this point, we would like to compute how many iterations of the loop the
1492 // predicate will return true for these inputs.
1493 if (isa<SCEVConstant>(LHS) && !isa<SCEVConstant>(RHS)) {
1494 // If there is a constant, force it into the RHS.
1495 std::swap(LHS, RHS);
1496 Cond = SetCondInst::getSwappedCondition(Cond);
1497 }
1498
1499 // FIXME: think about handling pointer comparisons! i.e.:
1500 // while (P != P+100) ++P;
1501
1502 // If we have a comparison of a chrec against a constant, try to use value
1503 // ranges to answer this query.
1504 if (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
1505 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
1506 if (AddRec->getLoop() == L) {
1507 // Form the comparison range using the constant of the correct type so
1508 // that the ConstantRange class knows to do a signed or unsigned
1509 // comparison.
1510 ConstantInt *CompVal = RHSC->getValue();
1511 const Type *RealTy = ExitCond->getOperand(0)->getType();
1512 CompVal = dyn_cast<ConstantInt>(ConstantExpr::getCast(CompVal, RealTy));
1513 if (CompVal) {
1514 // Form the constant range.
1515 ConstantRange CompRange(Cond, CompVal);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001516
Chris Lattner53e677a2004-04-02 20:23:17 +00001517 // Now that we have it, if it's signed, convert it to an unsigned
1518 // range.
1519 if (CompRange.getLower()->getType()->isSigned()) {
1520 const Type *NewTy = RHSC->getValue()->getType();
1521 Constant *NewL = ConstantExpr::getCast(CompRange.getLower(), NewTy);
1522 Constant *NewU = ConstantExpr::getCast(CompRange.getUpper(), NewTy);
1523 CompRange = ConstantRange(NewL, NewU);
1524 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001525
Chris Lattner53e677a2004-04-02 20:23:17 +00001526 SCEVHandle Ret = AddRec->getNumIterationsInRange(CompRange);
1527 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
1528 }
1529 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001530
Chris Lattner53e677a2004-04-02 20:23:17 +00001531 switch (Cond) {
1532 case Instruction::SetNE: // while (X != Y)
1533 // Convert to: while (X-Y != 0)
Chris Lattner7980fb92004-04-17 18:36:24 +00001534 if (LHS->getType()->isInteger()) {
Chris Lattnerbac5b462005-03-09 05:34:41 +00001535 SCEVHandle TC = HowFarToZero(SCEV::getMinusSCEV(LHS, RHS), L);
Chris Lattner7980fb92004-04-17 18:36:24 +00001536 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
1537 }
Chris Lattner53e677a2004-04-02 20:23:17 +00001538 break;
1539 case Instruction::SetEQ:
1540 // Convert to: while (X-Y == 0) // while (X == Y)
Chris Lattner7980fb92004-04-17 18:36:24 +00001541 if (LHS->getType()->isInteger()) {
Chris Lattnerbac5b462005-03-09 05:34:41 +00001542 SCEVHandle TC = HowFarToNonZero(SCEV::getMinusSCEV(LHS, RHS), L);
Chris Lattner7980fb92004-04-17 18:36:24 +00001543 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
1544 }
Chris Lattner53e677a2004-04-02 20:23:17 +00001545 break;
Chris Lattnerdb25de42005-08-15 23:33:51 +00001546 case Instruction::SetLT:
1547 if (LHS->getType()->isInteger() &&
1548 ExitCond->getOperand(0)->getType()->isSigned()) {
1549 SCEVHandle TC = HowManyLessThans(LHS, RHS, L);
1550 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
1551 }
1552 break;
1553 case Instruction::SetGT:
1554 if (LHS->getType()->isInteger() &&
1555 ExitCond->getOperand(0)->getType()->isSigned()) {
1556 SCEVHandle TC = HowManyLessThans(RHS, LHS, L);
1557 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
1558 }
1559 break;
Chris Lattner53e677a2004-04-02 20:23:17 +00001560 default:
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00001561#if 0
Bill Wendling6f81b512006-11-28 22:46:12 +00001562 llvm_cerr << "ComputeIterationCount ";
Chris Lattner53e677a2004-04-02 20:23:17 +00001563 if (ExitCond->getOperand(0)->getType()->isUnsigned())
Bill Wendling6f81b512006-11-28 22:46:12 +00001564 llvm_cerr << "[unsigned] ";
1565 llvm_cerr << *LHS << " "
Chris Lattner53e677a2004-04-02 20:23:17 +00001566 << Instruction::getOpcodeName(Cond) << " " << *RHS << "\n";
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00001567#endif
Chris Lattnere34c0b42004-04-03 00:43:03 +00001568 break;
Chris Lattner53e677a2004-04-02 20:23:17 +00001569 }
Chris Lattner7980fb92004-04-17 18:36:24 +00001570
1571 return ComputeIterationCountExhaustively(L, ExitCond,
1572 ExitBr->getSuccessor(0) == ExitBlock);
1573}
1574
Chris Lattner673e02b2004-10-12 01:49:27 +00001575static ConstantInt *
1576EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, Constant *C) {
1577 SCEVHandle InVal = SCEVConstant::get(cast<ConstantInt>(C));
1578 SCEVHandle Val = AddRec->evaluateAtIteration(InVal);
1579 assert(isa<SCEVConstant>(Val) &&
1580 "Evaluation of SCEV at constant didn't fold correctly?");
1581 return cast<SCEVConstant>(Val)->getValue();
1582}
1583
1584/// GetAddressedElementFromGlobal - Given a global variable with an initializer
1585/// and a GEP expression (missing the pointer index) indexing into it, return
1586/// the addressed element of the initializer or null if the index expression is
1587/// invalid.
1588static Constant *
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001589GetAddressedElementFromGlobal(GlobalVariable *GV,
Chris Lattner673e02b2004-10-12 01:49:27 +00001590 const std::vector<ConstantInt*> &Indices) {
1591 Constant *Init = GV->getInitializer();
1592 for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
Reid Spencerb83eb642006-10-20 07:07:24 +00001593 uint64_t Idx = Indices[i]->getZExtValue();
Chris Lattner673e02b2004-10-12 01:49:27 +00001594 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
1595 assert(Idx < CS->getNumOperands() && "Bad struct index!");
1596 Init = cast<Constant>(CS->getOperand(Idx));
1597 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
1598 if (Idx >= CA->getNumOperands()) return 0; // Bogus program
1599 Init = cast<Constant>(CA->getOperand(Idx));
1600 } else if (isa<ConstantAggregateZero>(Init)) {
1601 if (const StructType *STy = dyn_cast<StructType>(Init->getType())) {
1602 assert(Idx < STy->getNumElements() && "Bad struct index!");
1603 Init = Constant::getNullValue(STy->getElementType(Idx));
1604 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Init->getType())) {
1605 if (Idx >= ATy->getNumElements()) return 0; // Bogus program
1606 Init = Constant::getNullValue(ATy->getElementType());
1607 } else {
1608 assert(0 && "Unknown constant aggregate type!");
1609 }
1610 return 0;
1611 } else {
1612 return 0; // Unknown initializer type
1613 }
1614 }
1615 return Init;
1616}
1617
1618/// ComputeLoadConstantCompareIterationCount - Given an exit condition of
1619/// 'setcc load X, cst', try to se if we can compute the trip count.
1620SCEVHandle ScalarEvolutionsImpl::
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001621ComputeLoadConstantCompareIterationCount(LoadInst *LI, Constant *RHS,
Chris Lattner673e02b2004-10-12 01:49:27 +00001622 const Loop *L, unsigned SetCCOpcode) {
1623 if (LI->isVolatile()) return UnknownValue;
1624
1625 // Check to see if the loaded pointer is a getelementptr of a global.
1626 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
1627 if (!GEP) return UnknownValue;
1628
1629 // Make sure that it is really a constant global we are gepping, with an
1630 // initializer, and make sure the first IDX is really 0.
1631 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
1632 if (!GV || !GV->isConstant() || !GV->hasInitializer() ||
1633 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
1634 !cast<Constant>(GEP->getOperand(1))->isNullValue())
1635 return UnknownValue;
1636
1637 // Okay, we allow one non-constant index into the GEP instruction.
1638 Value *VarIdx = 0;
1639 std::vector<ConstantInt*> Indexes;
1640 unsigned VarIdxNum = 0;
1641 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
1642 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
1643 Indexes.push_back(CI);
1644 } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
1645 if (VarIdx) return UnknownValue; // Multiple non-constant idx's.
1646 VarIdx = GEP->getOperand(i);
1647 VarIdxNum = i-2;
1648 Indexes.push_back(0);
1649 }
1650
1651 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
1652 // Check to see if X is a loop variant variable value now.
1653 SCEVHandle Idx = getSCEV(VarIdx);
1654 SCEVHandle Tmp = getSCEVAtScope(Idx, L);
1655 if (!isa<SCEVCouldNotCompute>(Tmp)) Idx = Tmp;
1656
1657 // We can only recognize very limited forms of loop index expressions, in
1658 // particular, only affine AddRec's like {C1,+,C2}.
1659 SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
1660 if (!IdxExpr || !IdxExpr->isAffine() || IdxExpr->isLoopInvariant(L) ||
1661 !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
1662 !isa<SCEVConstant>(IdxExpr->getOperand(1)))
1663 return UnknownValue;
1664
1665 unsigned MaxSteps = MaxBruteForceIterations;
1666 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
Reid Spencerb83eb642006-10-20 07:07:24 +00001667 ConstantInt *ItCst =
1668 ConstantInt::get(IdxExpr->getType()->getUnsignedVersion(), IterationNum);
Chris Lattner673e02b2004-10-12 01:49:27 +00001669 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst);
1670
1671 // Form the GEP offset.
1672 Indexes[VarIdxNum] = Val;
1673
1674 Constant *Result = GetAddressedElementFromGlobal(GV, Indexes);
1675 if (Result == 0) break; // Cannot compute!
1676
1677 // Evaluate the condition for this iteration.
1678 Result = ConstantExpr::get(SetCCOpcode, Result, RHS);
1679 if (!isa<ConstantBool>(Result)) break; // Couldn't decide for sure
Chris Lattner003cbf32006-09-28 23:36:21 +00001680 if (cast<ConstantBool>(Result)->getValue() == false) {
Chris Lattner673e02b2004-10-12 01:49:27 +00001681#if 0
Bill Wendling6f81b512006-11-28 22:46:12 +00001682 llvm_cerr << "\n***\n*** Computed loop count " << *ItCst
Chris Lattner673e02b2004-10-12 01:49:27 +00001683 << "\n*** From global " << *GV << "*** BB: " << *L->getHeader()
1684 << "***\n";
1685#endif
1686 ++NumArrayLenItCounts;
1687 return SCEVConstant::get(ItCst); // Found terminating iteration!
1688 }
1689 }
1690 return UnknownValue;
1691}
1692
1693
Chris Lattner3221ad02004-04-17 22:58:41 +00001694/// CanConstantFold - Return true if we can constant fold an instruction of the
1695/// specified type, assuming that all operands were constants.
1696static bool CanConstantFold(const Instruction *I) {
1697 if (isa<BinaryOperator>(I) || isa<ShiftInst>(I) ||
1698 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I))
1699 return true;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001700
Chris Lattner3221ad02004-04-17 22:58:41 +00001701 if (const CallInst *CI = dyn_cast<CallInst>(I))
1702 if (const Function *F = CI->getCalledFunction())
1703 return canConstantFoldCallTo((Function*)F); // FIXME: elim cast
1704 return false;
Chris Lattner7980fb92004-04-17 18:36:24 +00001705}
1706
Chris Lattner3221ad02004-04-17 22:58:41 +00001707/// ConstantFold - Constant fold an instruction of the specified type with the
1708/// specified constant operands. This function may modify the operands vector.
1709static Constant *ConstantFold(const Instruction *I,
1710 std::vector<Constant*> &Operands) {
Chris Lattner7980fb92004-04-17 18:36:24 +00001711 if (isa<BinaryOperator>(I) || isa<ShiftInst>(I))
1712 return ConstantExpr::get(I->getOpcode(), Operands[0], Operands[1]);
1713
Reid Spencer3da59db2006-11-27 01:05:10 +00001714 if (isa<CastInst>(I))
1715 return ConstantExpr::getCast(I->getOpcode(), Operands[0], I->getType());
1716
Chris Lattner7980fb92004-04-17 18:36:24 +00001717 switch (I->getOpcode()) {
Chris Lattner7980fb92004-04-17 18:36:24 +00001718 case Instruction::Select:
1719 return ConstantExpr::getSelect(Operands[0], Operands[1], Operands[2]);
1720 case Instruction::Call:
Reid Spencere8404342004-07-18 00:18:30 +00001721 if (Function *GV = dyn_cast<Function>(Operands[0])) {
Chris Lattner7980fb92004-04-17 18:36:24 +00001722 Operands.erase(Operands.begin());
Reid Spencere8404342004-07-18 00:18:30 +00001723 return ConstantFoldCall(cast<Function>(GV), Operands);
Chris Lattner7980fb92004-04-17 18:36:24 +00001724 }
Chris Lattner7980fb92004-04-17 18:36:24 +00001725 return 0;
1726 case Instruction::GetElementPtr:
1727 Constant *Base = Operands[0];
1728 Operands.erase(Operands.begin());
1729 return ConstantExpr::getGetElementPtr(Base, Operands);
1730 }
1731 return 0;
1732}
1733
1734
Chris Lattner3221ad02004-04-17 22:58:41 +00001735/// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
1736/// in the loop that V is derived from. We allow arbitrary operations along the
1737/// way, but the operands of an operation must either be constants or a value
1738/// derived from a constant PHI. If this expression does not fit with these
1739/// constraints, return null.
1740static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
1741 // If this is not an instruction, or if this is an instruction outside of the
1742 // loop, it can't be derived from a loop PHI.
1743 Instruction *I = dyn_cast<Instruction>(V);
1744 if (I == 0 || !L->contains(I->getParent())) return 0;
1745
1746 if (PHINode *PN = dyn_cast<PHINode>(I))
1747 if (L->getHeader() == I->getParent())
1748 return PN;
1749 else
1750 // We don't currently keep track of the control flow needed to evaluate
1751 // PHIs, so we cannot handle PHIs inside of loops.
1752 return 0;
1753
1754 // If we won't be able to constant fold this expression even if the operands
1755 // are constants, return early.
1756 if (!CanConstantFold(I)) return 0;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001757
Chris Lattner3221ad02004-04-17 22:58:41 +00001758 // Otherwise, we can evaluate this instruction if all of its operands are
1759 // constant or derived from a PHI node themselves.
1760 PHINode *PHI = 0;
1761 for (unsigned Op = 0, e = I->getNumOperands(); Op != e; ++Op)
1762 if (!(isa<Constant>(I->getOperand(Op)) ||
1763 isa<GlobalValue>(I->getOperand(Op)))) {
1764 PHINode *P = getConstantEvolvingPHI(I->getOperand(Op), L);
1765 if (P == 0) return 0; // Not evolving from PHI
1766 if (PHI == 0)
1767 PHI = P;
1768 else if (PHI != P)
1769 return 0; // Evolving from multiple different PHIs.
1770 }
1771
1772 // This is a expression evolving from a constant PHI!
1773 return PHI;
1774}
1775
1776/// EvaluateExpression - Given an expression that passes the
1777/// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
1778/// in the loop has the value PHIVal. If we can't fold this expression for some
1779/// reason, return null.
1780static Constant *EvaluateExpression(Value *V, Constant *PHIVal) {
1781 if (isa<PHINode>(V)) return PHIVal;
Chris Lattner3221ad02004-04-17 22:58:41 +00001782 if (GlobalValue *GV = dyn_cast<GlobalValue>(V))
Reid Spencere8404342004-07-18 00:18:30 +00001783 return GV;
1784 if (Constant *C = dyn_cast<Constant>(V)) return C;
Chris Lattner3221ad02004-04-17 22:58:41 +00001785 Instruction *I = cast<Instruction>(V);
1786
1787 std::vector<Constant*> Operands;
1788 Operands.resize(I->getNumOperands());
1789
1790 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
1791 Operands[i] = EvaluateExpression(I->getOperand(i), PHIVal);
1792 if (Operands[i] == 0) return 0;
1793 }
1794
1795 return ConstantFold(I, Operands);
1796}
1797
1798/// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
1799/// in the header of its containing loop, we know the loop executes a
1800/// constant number of times, and the PHI node is just a recurrence
1801/// involving constants, fold it.
1802Constant *ScalarEvolutionsImpl::
1803getConstantEvolutionLoopExitValue(PHINode *PN, uint64_t Its, const Loop *L) {
1804 std::map<PHINode*, Constant*>::iterator I =
1805 ConstantEvolutionLoopExitValue.find(PN);
1806 if (I != ConstantEvolutionLoopExitValue.end())
1807 return I->second;
1808
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001809 if (Its > MaxBruteForceIterations)
Chris Lattner3221ad02004-04-17 22:58:41 +00001810 return ConstantEvolutionLoopExitValue[PN] = 0; // Not going to evaluate it.
1811
1812 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
1813
1814 // Since the loop is canonicalized, the PHI node must have two entries. One
1815 // entry must be a constant (coming in from outside of the loop), and the
1816 // second must be derived from the same PHI.
1817 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
1818 Constant *StartCST =
1819 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
1820 if (StartCST == 0)
1821 return RetVal = 0; // Must be a constant.
1822
1823 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
1824 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
1825 if (PN2 != PN)
1826 return RetVal = 0; // Not derived from same PHI.
1827
1828 // Execute the loop symbolically to determine the exit value.
1829 unsigned IterationNum = 0;
1830 unsigned NumIterations = Its;
1831 if (NumIterations != Its)
1832 return RetVal = 0; // More than 2^32 iterations??
1833
1834 for (Constant *PHIVal = StartCST; ; ++IterationNum) {
1835 if (IterationNum == NumIterations)
1836 return RetVal = PHIVal; // Got exit value!
1837
1838 // Compute the value of the PHI node for the next iteration.
1839 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
1840 if (NextPHI == PHIVal)
1841 return RetVal = NextPHI; // Stopped evolving!
1842 if (NextPHI == 0)
1843 return 0; // Couldn't evaluate!
1844 PHIVal = NextPHI;
1845 }
1846}
1847
Chris Lattner7980fb92004-04-17 18:36:24 +00001848/// ComputeIterationCountExhaustively - If the trip is known to execute a
1849/// constant number of times (the condition evolves only from constants),
1850/// try to evaluate a few iterations of the loop until we get the exit
1851/// condition gets a value of ExitWhen (true or false). If we cannot
1852/// evaluate the trip count of the loop, return UnknownValue.
1853SCEVHandle ScalarEvolutionsImpl::
1854ComputeIterationCountExhaustively(const Loop *L, Value *Cond, bool ExitWhen) {
1855 PHINode *PN = getConstantEvolvingPHI(Cond, L);
1856 if (PN == 0) return UnknownValue;
1857
1858 // Since the loop is canonicalized, the PHI node must have two entries. One
1859 // entry must be a constant (coming in from outside of the loop), and the
1860 // second must be derived from the same PHI.
1861 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
1862 Constant *StartCST =
1863 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
1864 if (StartCST == 0) return UnknownValue; // Must be a constant.
1865
1866 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
1867 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
1868 if (PN2 != PN) return UnknownValue; // Not derived from same PHI.
1869
1870 // Okay, we find a PHI node that defines the trip count of this loop. Execute
1871 // the loop symbolically to determine when the condition gets a value of
1872 // "ExitWhen".
1873 unsigned IterationNum = 0;
1874 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis.
1875 for (Constant *PHIVal = StartCST;
1876 IterationNum != MaxIterations; ++IterationNum) {
1877 ConstantBool *CondVal =
1878 dyn_cast_or_null<ConstantBool>(EvaluateExpression(Cond, PHIVal));
1879 if (!CondVal) return UnknownValue; // Couldn't symbolically evaluate.
Chris Lattner3221ad02004-04-17 22:58:41 +00001880
Chris Lattner7980fb92004-04-17 18:36:24 +00001881 if (CondVal->getValue() == ExitWhen) {
Chris Lattner3221ad02004-04-17 22:58:41 +00001882 ConstantEvolutionLoopExitValue[PN] = PHIVal;
Chris Lattner7980fb92004-04-17 18:36:24 +00001883 ++NumBruteForceTripCountsComputed;
Reid Spencerb83eb642006-10-20 07:07:24 +00001884 return SCEVConstant::get(ConstantInt::get(Type::UIntTy, IterationNum));
Chris Lattner7980fb92004-04-17 18:36:24 +00001885 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001886
Chris Lattner3221ad02004-04-17 22:58:41 +00001887 // Compute the value of the PHI node for the next iteration.
1888 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
1889 if (NextPHI == 0 || NextPHI == PHIVal)
Chris Lattner7980fb92004-04-17 18:36:24 +00001890 return UnknownValue; // Couldn't evaluate or not making progress...
Chris Lattner3221ad02004-04-17 22:58:41 +00001891 PHIVal = NextPHI;
Chris Lattner7980fb92004-04-17 18:36:24 +00001892 }
1893
1894 // Too many iterations were needed to evaluate.
Chris Lattner53e677a2004-04-02 20:23:17 +00001895 return UnknownValue;
1896}
1897
1898/// getSCEVAtScope - Compute the value of the specified expression within the
1899/// indicated loop (which may be null to indicate in no loop). If the
1900/// expression cannot be evaluated, return UnknownValue.
1901SCEVHandle ScalarEvolutionsImpl::getSCEVAtScope(SCEV *V, const Loop *L) {
1902 // FIXME: this should be turned into a virtual method on SCEV!
1903
Chris Lattner3221ad02004-04-17 22:58:41 +00001904 if (isa<SCEVConstant>(V)) return V;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001905
Chris Lattner3221ad02004-04-17 22:58:41 +00001906 // If this instruction is evolves from a constant-evolving PHI, compute the
1907 // exit value from the loop without using SCEVs.
1908 if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
1909 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
1910 const Loop *LI = this->LI[I->getParent()];
1911 if (LI && LI->getParentLoop() == L) // Looking for loop exit value.
1912 if (PHINode *PN = dyn_cast<PHINode>(I))
1913 if (PN->getParent() == LI->getHeader()) {
1914 // Okay, there is no closed form solution for the PHI node. Check
1915 // to see if the loop that contains it has a known iteration count.
1916 // If so, we may be able to force computation of the exit value.
1917 SCEVHandle IterationCount = getIterationCount(LI);
1918 if (SCEVConstant *ICC = dyn_cast<SCEVConstant>(IterationCount)) {
1919 // Okay, we know how many times the containing loop executes. If
1920 // this is a constant evolving PHI node, get the final value at
1921 // the specified iteration number.
1922 Constant *RV = getConstantEvolutionLoopExitValue(PN,
Reid Spencerb83eb642006-10-20 07:07:24 +00001923 ICC->getValue()->getZExtValue(),
Chris Lattner3221ad02004-04-17 22:58:41 +00001924 LI);
1925 if (RV) return SCEVUnknown::get(RV);
1926 }
1927 }
1928
Reid Spencer09906f32006-12-04 21:33:23 +00001929 // Okay, this is an expression that we cannot symbolically evaluate
Chris Lattner3221ad02004-04-17 22:58:41 +00001930 // into a SCEV. Check to see if it's possible to symbolically evaluate
Reid Spencer09906f32006-12-04 21:33:23 +00001931 // the arguments into constants, and if so, try to constant propagate the
Chris Lattner3221ad02004-04-17 22:58:41 +00001932 // result. This is particularly useful for computing loop exit values.
1933 if (CanConstantFold(I)) {
1934 std::vector<Constant*> Operands;
1935 Operands.reserve(I->getNumOperands());
1936 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
1937 Value *Op = I->getOperand(i);
1938 if (Constant *C = dyn_cast<Constant>(Op)) {
1939 Operands.push_back(C);
Chris Lattner3221ad02004-04-17 22:58:41 +00001940 } else {
1941 SCEVHandle OpV = getSCEVAtScope(getSCEV(Op), L);
1942 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(OpV))
1943 Operands.push_back(ConstantExpr::getCast(SC->getValue(),
1944 Op->getType()));
1945 else if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(OpV)) {
1946 if (Constant *C = dyn_cast<Constant>(SU->getValue()))
1947 Operands.push_back(ConstantExpr::getCast(C, Op->getType()));
1948 else
1949 return V;
1950 } else {
1951 return V;
1952 }
1953 }
1954 }
1955 return SCEVUnknown::get(ConstantFold(I, Operands));
1956 }
1957 }
1958
1959 // This is some other type of SCEVUnknown, just return it.
1960 return V;
1961 }
1962
Chris Lattner53e677a2004-04-02 20:23:17 +00001963 if (SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
1964 // Avoid performing the look-up in the common case where the specified
1965 // expression has no loop-variant portions.
1966 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
1967 SCEVHandle OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
1968 if (OpAtScope != Comm->getOperand(i)) {
1969 if (OpAtScope == UnknownValue) return UnknownValue;
1970 // Okay, at least one of these operands is loop variant but might be
1971 // foldable. Build a new instance of the folded commutative expression.
Chris Lattner3221ad02004-04-17 22:58:41 +00001972 std::vector<SCEVHandle> NewOps(Comm->op_begin(), Comm->op_begin()+i);
Chris Lattner53e677a2004-04-02 20:23:17 +00001973 NewOps.push_back(OpAtScope);
1974
1975 for (++i; i != e; ++i) {
1976 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
1977 if (OpAtScope == UnknownValue) return UnknownValue;
1978 NewOps.push_back(OpAtScope);
1979 }
1980 if (isa<SCEVAddExpr>(Comm))
1981 return SCEVAddExpr::get(NewOps);
1982 assert(isa<SCEVMulExpr>(Comm) && "Only know about add and mul!");
1983 return SCEVMulExpr::get(NewOps);
1984 }
1985 }
1986 // If we got here, all operands are loop invariant.
1987 return Comm;
1988 }
1989
Chris Lattner60a05cc2006-04-01 04:48:52 +00001990 if (SCEVSDivExpr *Div = dyn_cast<SCEVSDivExpr>(V)) {
1991 SCEVHandle LHS = getSCEVAtScope(Div->getLHS(), L);
Chris Lattner53e677a2004-04-02 20:23:17 +00001992 if (LHS == UnknownValue) return LHS;
Chris Lattner60a05cc2006-04-01 04:48:52 +00001993 SCEVHandle RHS = getSCEVAtScope(Div->getRHS(), L);
Chris Lattner53e677a2004-04-02 20:23:17 +00001994 if (RHS == UnknownValue) return RHS;
Chris Lattner60a05cc2006-04-01 04:48:52 +00001995 if (LHS == Div->getLHS() && RHS == Div->getRHS())
1996 return Div; // must be loop invariant
1997 return SCEVSDivExpr::get(LHS, RHS);
Chris Lattner53e677a2004-04-02 20:23:17 +00001998 }
1999
2000 // If this is a loop recurrence for a loop that does not contain L, then we
2001 // are dealing with the final value computed by the loop.
2002 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
2003 if (!L || !AddRec->getLoop()->contains(L->getHeader())) {
2004 // To evaluate this recurrence, we need to know how many times the AddRec
2005 // loop iterates. Compute this now.
2006 SCEVHandle IterationCount = getIterationCount(AddRec->getLoop());
2007 if (IterationCount == UnknownValue) return UnknownValue;
2008 IterationCount = getTruncateOrZeroExtend(IterationCount,
2009 AddRec->getType());
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002010
Chris Lattner53e677a2004-04-02 20:23:17 +00002011 // If the value is affine, simplify the expression evaluation to just
2012 // Start + Step*IterationCount.
2013 if (AddRec->isAffine())
2014 return SCEVAddExpr::get(AddRec->getStart(),
2015 SCEVMulExpr::get(IterationCount,
2016 AddRec->getOperand(1)));
2017
2018 // Otherwise, evaluate it the hard way.
2019 return AddRec->evaluateAtIteration(IterationCount);
2020 }
2021 return UnknownValue;
2022 }
2023
2024 //assert(0 && "Unknown SCEV type!");
2025 return UnknownValue;
2026}
2027
2028
2029/// SolveQuadraticEquation - Find the roots of the quadratic equation for the
2030/// given quadratic chrec {L,+,M,+,N}. This returns either the two roots (which
2031/// might be the same) or two SCEVCouldNotCompute objects.
2032///
2033static std::pair<SCEVHandle,SCEVHandle>
2034SolveQuadraticEquation(const SCEVAddRecExpr *AddRec) {
2035 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
2036 SCEVConstant *L = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
2037 SCEVConstant *M = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
2038 SCEVConstant *N = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002039
Chris Lattner53e677a2004-04-02 20:23:17 +00002040 // We currently can only solve this if the coefficients are constants.
2041 if (!L || !M || !N) {
2042 SCEV *CNC = new SCEVCouldNotCompute();
2043 return std::make_pair(CNC, CNC);
2044 }
2045
Reid Spencer1628cec2006-10-26 06:15:43 +00002046 Constant *C = L->getValue();
2047 Constant *Two = ConstantInt::get(C->getType(), 2);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002048
Chris Lattner53e677a2004-04-02 20:23:17 +00002049 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
Chris Lattner53e677a2004-04-02 20:23:17 +00002050 // The B coefficient is M-N/2
2051 Constant *B = ConstantExpr::getSub(M->getValue(),
Reid Spencer1628cec2006-10-26 06:15:43 +00002052 ConstantExpr::getSDiv(N->getValue(),
Chris Lattner53e677a2004-04-02 20:23:17 +00002053 Two));
2054 // The A coefficient is N/2
Reid Spencer1628cec2006-10-26 06:15:43 +00002055 Constant *A = ConstantExpr::getSDiv(N->getValue(), Two);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002056
Chris Lattner53e677a2004-04-02 20:23:17 +00002057 // Compute the B^2-4ac term.
2058 Constant *SqrtTerm =
2059 ConstantExpr::getMul(ConstantInt::get(C->getType(), 4),
2060 ConstantExpr::getMul(A, C));
2061 SqrtTerm = ConstantExpr::getSub(ConstantExpr::getMul(B, B), SqrtTerm);
2062
2063 // Compute floor(sqrt(B^2-4ac))
Reid Spencerb83eb642006-10-20 07:07:24 +00002064 ConstantInt *SqrtVal =
2065 cast<ConstantInt>(ConstantExpr::getCast(SqrtTerm,
Chris Lattner53e677a2004-04-02 20:23:17 +00002066 SqrtTerm->getType()->getUnsignedVersion()));
Reid Spencerb83eb642006-10-20 07:07:24 +00002067 uint64_t SqrtValV = SqrtVal->getZExtValue();
Chris Lattner219c1412004-10-25 18:40:08 +00002068 uint64_t SqrtValV2 = (uint64_t)sqrt((double)SqrtValV);
Chris Lattner53e677a2004-04-02 20:23:17 +00002069 // The square root might not be precise for arbitrary 64-bit integer
2070 // values. Do some sanity checks to ensure it's correct.
2071 if (SqrtValV2*SqrtValV2 > SqrtValV ||
2072 (SqrtValV2+1)*(SqrtValV2+1) <= SqrtValV) {
2073 SCEV *CNC = new SCEVCouldNotCompute();
2074 return std::make_pair(CNC, CNC);
2075 }
2076
Reid Spencerb83eb642006-10-20 07:07:24 +00002077 SqrtVal = ConstantInt::get(Type::ULongTy, SqrtValV2);
Chris Lattner53e677a2004-04-02 20:23:17 +00002078 SqrtTerm = ConstantExpr::getCast(SqrtVal, SqrtTerm->getType());
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002079
Chris Lattner53e677a2004-04-02 20:23:17 +00002080 Constant *NegB = ConstantExpr::getNeg(B);
2081 Constant *TwoA = ConstantExpr::getMul(A, Two);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002082
Chris Lattner53e677a2004-04-02 20:23:17 +00002083 // The divisions must be performed as signed divisions.
2084 const Type *SignedTy = NegB->getType()->getSignedVersion();
2085 NegB = ConstantExpr::getCast(NegB, SignedTy);
2086 TwoA = ConstantExpr::getCast(TwoA, SignedTy);
2087 SqrtTerm = ConstantExpr::getCast(SqrtTerm, SignedTy);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002088
Chris Lattner53e677a2004-04-02 20:23:17 +00002089 Constant *Solution1 =
Reid Spencer1628cec2006-10-26 06:15:43 +00002090 ConstantExpr::getSDiv(ConstantExpr::getAdd(NegB, SqrtTerm), TwoA);
Chris Lattner53e677a2004-04-02 20:23:17 +00002091 Constant *Solution2 =
Reid Spencer1628cec2006-10-26 06:15:43 +00002092 ConstantExpr::getSDiv(ConstantExpr::getSub(NegB, SqrtTerm), TwoA);
Chris Lattner53e677a2004-04-02 20:23:17 +00002093 return std::make_pair(SCEVUnknown::get(Solution1),
2094 SCEVUnknown::get(Solution2));
2095}
2096
2097/// HowFarToZero - Return the number of times a backedge comparing the specified
2098/// value to zero will execute. If not computable, return UnknownValue
2099SCEVHandle ScalarEvolutionsImpl::HowFarToZero(SCEV *V, const Loop *L) {
2100 // If the value is a constant
2101 if (SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
2102 // If the value is already zero, the branch will execute zero times.
2103 if (C->getValue()->isNullValue()) return C;
2104 return UnknownValue; // Otherwise it will loop infinitely.
2105 }
2106
2107 SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
2108 if (!AddRec || AddRec->getLoop() != L)
2109 return UnknownValue;
2110
2111 if (AddRec->isAffine()) {
2112 // If this is an affine expression the execution count of this branch is
2113 // equal to:
2114 //
2115 // (0 - Start/Step) iff Start % Step == 0
2116 //
2117 // Get the initial value for the loop.
2118 SCEVHandle Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
Chris Lattner4a2b23e2004-10-11 04:07:27 +00002119 if (isa<SCEVCouldNotCompute>(Start)) return UnknownValue;
Chris Lattner53e677a2004-04-02 20:23:17 +00002120 SCEVHandle Step = AddRec->getOperand(1);
2121
2122 Step = getSCEVAtScope(Step, L->getParentLoop());
2123
2124 // Figure out if Start % Step == 0.
2125 // FIXME: We should add DivExpr and RemExpr operations to our AST.
2126 if (SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step)) {
2127 if (StepC->getValue()->equalsInt(1)) // N % 1 == 0
Chris Lattnerbac5b462005-03-09 05:34:41 +00002128 return SCEV::getNegativeSCEV(Start); // 0 - Start/1 == -Start
Chris Lattner53e677a2004-04-02 20:23:17 +00002129 if (StepC->getValue()->isAllOnesValue()) // N % -1 == 0
2130 return Start; // 0 - Start/-1 == Start
2131
2132 // Check to see if Start is divisible by SC with no remainder.
2133 if (SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start)) {
2134 ConstantInt *StartCC = StartC->getValue();
2135 Constant *StartNegC = ConstantExpr::getNeg(StartCC);
Reid Spencer0a783f72006-11-02 01:53:59 +00002136 Constant *Rem = ConstantExpr::getSRem(StartNegC, StepC->getValue());
Chris Lattner53e677a2004-04-02 20:23:17 +00002137 if (Rem->isNullValue()) {
Reid Spencer1628cec2006-10-26 06:15:43 +00002138 Constant *Result =ConstantExpr::getSDiv(StartNegC,StepC->getValue());
Chris Lattner53e677a2004-04-02 20:23:17 +00002139 return SCEVUnknown::get(Result);
2140 }
2141 }
2142 }
2143 } else if (AddRec->isQuadratic() && AddRec->getType()->isInteger()) {
2144 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
2145 // the quadratic equation to solve it.
2146 std::pair<SCEVHandle,SCEVHandle> Roots = SolveQuadraticEquation(AddRec);
2147 SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
2148 SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
2149 if (R1) {
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00002150#if 0
Bill Wendling6f81b512006-11-28 22:46:12 +00002151 llvm_cerr << "HFTZ: " << *V << " - sol#1: " << *R1
Chris Lattner53e677a2004-04-02 20:23:17 +00002152 << " sol#2: " << *R2 << "\n";
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00002153#endif
Chris Lattner53e677a2004-04-02 20:23:17 +00002154 // Pick the smallest positive root value.
2155 assert(R1->getType()->isUnsigned()&&"Didn't canonicalize to unsigned?");
2156 if (ConstantBool *CB =
2157 dyn_cast<ConstantBool>(ConstantExpr::getSetLT(R1->getValue(),
2158 R2->getValue()))) {
Chris Lattner003cbf32006-09-28 23:36:21 +00002159 if (CB->getValue() == false)
Chris Lattner53e677a2004-04-02 20:23:17 +00002160 std::swap(R1, R2); // R1 is the minimum root now.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002161
Chris Lattner53e677a2004-04-02 20:23:17 +00002162 // We can only use this value if the chrec ends up with an exact zero
2163 // value at this index. When solving for "X*X != 5", for example, we
2164 // should not accept a root of 2.
2165 SCEVHandle Val = AddRec->evaluateAtIteration(R1);
2166 if (SCEVConstant *EvalVal = dyn_cast<SCEVConstant>(Val))
2167 if (EvalVal->getValue()->isNullValue())
2168 return R1; // We found a quadratic root!
2169 }
2170 }
2171 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002172
Chris Lattner53e677a2004-04-02 20:23:17 +00002173 return UnknownValue;
2174}
2175
2176/// HowFarToNonZero - Return the number of times a backedge checking the
2177/// specified value for nonzero will execute. If not computable, return
2178/// UnknownValue
2179SCEVHandle ScalarEvolutionsImpl::HowFarToNonZero(SCEV *V, const Loop *L) {
2180 // Loops that look like: while (X == 0) are very strange indeed. We don't
2181 // handle them yet except for the trivial case. This could be expanded in the
2182 // future as needed.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002183
Chris Lattner53e677a2004-04-02 20:23:17 +00002184 // If the value is a constant, check to see if it is known to be non-zero
2185 // already. If so, the backedge will execute zero times.
2186 if (SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
2187 Constant *Zero = Constant::getNullValue(C->getValue()->getType());
2188 Constant *NonZero = ConstantExpr::getSetNE(C->getValue(), Zero);
Chris Lattner003cbf32006-09-28 23:36:21 +00002189 if (NonZero == ConstantBool::getTrue())
Chris Lattner53e677a2004-04-02 20:23:17 +00002190 return getSCEV(Zero);
2191 return UnknownValue; // Otherwise it will loop infinitely.
2192 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002193
Chris Lattner53e677a2004-04-02 20:23:17 +00002194 // We could implement others, but I really doubt anyone writes loops like
2195 // this, and if they did, they would already be constant folded.
2196 return UnknownValue;
2197}
2198
Chris Lattnerdb25de42005-08-15 23:33:51 +00002199/// HowManyLessThans - Return the number of times a backedge containing the
2200/// specified less-than comparison will execute. If not computable, return
2201/// UnknownValue.
2202SCEVHandle ScalarEvolutionsImpl::
2203HowManyLessThans(SCEV *LHS, SCEV *RHS, const Loop *L) {
2204 // Only handle: "ADDREC < LoopInvariant".
2205 if (!RHS->isLoopInvariant(L)) return UnknownValue;
2206
2207 SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS);
2208 if (!AddRec || AddRec->getLoop() != L)
2209 return UnknownValue;
2210
2211 if (AddRec->isAffine()) {
2212 // FORNOW: We only support unit strides.
2213 SCEVHandle One = SCEVUnknown::getIntegerSCEV(1, RHS->getType());
2214 if (AddRec->getOperand(1) != One)
2215 return UnknownValue;
2216
2217 // The number of iterations for "[n,+,1] < m", is m-n. However, we don't
2218 // know that m is >= n on input to the loop. If it is, the condition return
2219 // true zero times. What we really should return, for full generality, is
2220 // SMAX(0, m-n). Since we cannot check this, we will instead check for a
2221 // canonical loop form: most do-loops will have a check that dominates the
2222 // loop, that only enters the loop if [n-1]<m. If we can find this check,
2223 // we know that the SMAX will evaluate to m-n, because we know that m >= n.
2224
2225 // Search for the check.
2226 BasicBlock *Preheader = L->getLoopPreheader();
2227 BasicBlock *PreheaderDest = L->getHeader();
2228 if (Preheader == 0) return UnknownValue;
2229
2230 BranchInst *LoopEntryPredicate =
2231 dyn_cast<BranchInst>(Preheader->getTerminator());
2232 if (!LoopEntryPredicate) return UnknownValue;
2233
2234 // This might be a critical edge broken out. If the loop preheader ends in
2235 // an unconditional branch to the loop, check to see if the preheader has a
2236 // single predecessor, and if so, look for its terminator.
2237 while (LoopEntryPredicate->isUnconditional()) {
2238 PreheaderDest = Preheader;
2239 Preheader = Preheader->getSinglePredecessor();
2240 if (!Preheader) return UnknownValue; // Multiple preds.
2241
2242 LoopEntryPredicate =
2243 dyn_cast<BranchInst>(Preheader->getTerminator());
2244 if (!LoopEntryPredicate) return UnknownValue;
2245 }
2246
2247 // Now that we found a conditional branch that dominates the loop, check to
2248 // see if it is the comparison we are looking for.
2249 SetCondInst *SCI =dyn_cast<SetCondInst>(LoopEntryPredicate->getCondition());
2250 if (!SCI) return UnknownValue;
2251 Value *PreCondLHS = SCI->getOperand(0);
2252 Value *PreCondRHS = SCI->getOperand(1);
2253 Instruction::BinaryOps Cond;
2254 if (LoopEntryPredicate->getSuccessor(0) == PreheaderDest)
2255 Cond = SCI->getOpcode();
2256 else
2257 Cond = SCI->getInverseCondition();
2258
2259 switch (Cond) {
2260 case Instruction::SetGT:
2261 std::swap(PreCondLHS, PreCondRHS);
2262 Cond = Instruction::SetLT;
2263 // Fall Through.
2264 case Instruction::SetLT:
2265 if (PreCondLHS->getType()->isInteger() &&
2266 PreCondLHS->getType()->isSigned()) {
2267 if (RHS != getSCEV(PreCondRHS))
2268 return UnknownValue; // Not a comparison against 'm'.
2269
2270 if (SCEV::getMinusSCEV(AddRec->getOperand(0), One)
2271 != getSCEV(PreCondLHS))
2272 return UnknownValue; // Not a comparison against 'n-1'.
2273 break;
2274 } else {
2275 return UnknownValue;
2276 }
2277 default: break;
2278 }
2279
Bill Wendling6f81b512006-11-28 22:46:12 +00002280 //llvm_cerr << "Computed Loop Trip Count as: " <<
Chris Lattnerdb25de42005-08-15 23:33:51 +00002281 // *SCEV::getMinusSCEV(RHS, AddRec->getOperand(0)) << "\n";
2282 return SCEV::getMinusSCEV(RHS, AddRec->getOperand(0));
2283 }
2284
2285 return UnknownValue;
2286}
2287
Chris Lattner53e677a2004-04-02 20:23:17 +00002288/// getNumIterationsInRange - Return the number of iterations of this loop that
2289/// produce values in the specified constant range. Another way of looking at
2290/// this is that it returns the first iteration number where the value is not in
2291/// the condition, thus computing the exit count. If the iteration count can't
2292/// be computed, an instance of SCEVCouldNotCompute is returned.
2293SCEVHandle SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range) const {
2294 if (Range.isFullSet()) // Infinite loop.
2295 return new SCEVCouldNotCompute();
2296
2297 // If the start is a non-zero constant, shift the range to simplify things.
2298 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
2299 if (!SC->getValue()->isNullValue()) {
2300 std::vector<SCEVHandle> Operands(op_begin(), op_end());
Chris Lattnerb06432c2004-04-23 21:29:03 +00002301 Operands[0] = SCEVUnknown::getIntegerSCEV(0, SC->getType());
Chris Lattner53e677a2004-04-02 20:23:17 +00002302 SCEVHandle Shifted = SCEVAddRecExpr::get(Operands, getLoop());
2303 if (SCEVAddRecExpr *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted))
2304 return ShiftedAddRec->getNumIterationsInRange(
2305 Range.subtract(SC->getValue()));
2306 // This is strange and shouldn't happen.
2307 return new SCEVCouldNotCompute();
2308 }
2309
2310 // The only time we can solve this is when we have all constant indices.
2311 // Otherwise, we cannot determine the overflow conditions.
2312 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
2313 if (!isa<SCEVConstant>(getOperand(i)))
2314 return new SCEVCouldNotCompute();
2315
2316
2317 // Okay at this point we know that all elements of the chrec are constants and
2318 // that the start element is zero.
2319
2320 // First check to see if the range contains zero. If not, the first
2321 // iteration exits.
2322 ConstantInt *Zero = ConstantInt::get(getType(), 0);
2323 if (!Range.contains(Zero)) return SCEVConstant::get(Zero);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002324
Chris Lattner53e677a2004-04-02 20:23:17 +00002325 if (isAffine()) {
2326 // If this is an affine expression then we have this situation:
2327 // Solve {0,+,A} in Range === Ax in Range
2328
2329 // Since we know that zero is in the range, we know that the upper value of
2330 // the range must be the first possible exit value. Also note that we
2331 // already checked for a full range.
2332 ConstantInt *Upper = cast<ConstantInt>(Range.getUpper());
2333 ConstantInt *A = cast<SCEVConstant>(getOperand(1))->getValue();
2334 ConstantInt *One = ConstantInt::get(getType(), 1);
2335
2336 // The exit value should be (Upper+A-1)/A.
2337 Constant *ExitValue = Upper;
2338 if (A != One) {
2339 ExitValue = ConstantExpr::getSub(ConstantExpr::getAdd(Upper, A), One);
Reid Spencer1628cec2006-10-26 06:15:43 +00002340 ExitValue = ConstantExpr::getSDiv(ExitValue, A);
Chris Lattner53e677a2004-04-02 20:23:17 +00002341 }
2342 assert(isa<ConstantInt>(ExitValue) &&
2343 "Constant folding of integers not implemented?");
2344
2345 // Evaluate at the exit value. If we really did fall out of the valid
2346 // range, then we computed our trip count, otherwise wrap around or other
2347 // things must have happened.
2348 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue);
2349 if (Range.contains(Val))
2350 return new SCEVCouldNotCompute(); // Something strange happened
2351
2352 // Ensure that the previous value is in the range. This is a sanity check.
2353 assert(Range.contains(EvaluateConstantChrecAtConstant(this,
2354 ConstantExpr::getSub(ExitValue, One))) &&
2355 "Linear scev computation is off in a bad way!");
2356 return SCEVConstant::get(cast<ConstantInt>(ExitValue));
2357 } else if (isQuadratic()) {
2358 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
2359 // quadratic equation to solve it. To do this, we must frame our problem in
2360 // terms of figuring out when zero is crossed, instead of when
2361 // Range.getUpper() is crossed.
2362 std::vector<SCEVHandle> NewOps(op_begin(), op_end());
Chris Lattnerbac5b462005-03-09 05:34:41 +00002363 NewOps[0] = SCEV::getNegativeSCEV(SCEVUnknown::get(Range.getUpper()));
Chris Lattner53e677a2004-04-02 20:23:17 +00002364 SCEVHandle NewAddRec = SCEVAddRecExpr::get(NewOps, getLoop());
2365
2366 // Next, solve the constructed addrec
2367 std::pair<SCEVHandle,SCEVHandle> Roots =
2368 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec));
2369 SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
2370 SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
2371 if (R1) {
2372 // Pick the smallest positive root value.
2373 assert(R1->getType()->isUnsigned() && "Didn't canonicalize to unsigned?");
2374 if (ConstantBool *CB =
2375 dyn_cast<ConstantBool>(ConstantExpr::getSetLT(R1->getValue(),
2376 R2->getValue()))) {
Chris Lattner003cbf32006-09-28 23:36:21 +00002377 if (CB->getValue() == false)
Chris Lattner53e677a2004-04-02 20:23:17 +00002378 std::swap(R1, R2); // R1 is the minimum root now.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002379
Chris Lattner53e677a2004-04-02 20:23:17 +00002380 // Make sure the root is not off by one. The returned iteration should
2381 // not be in the range, but the previous one should be. When solving
2382 // for "X*X < 5", for example, we should not return a root of 2.
2383 ConstantInt *R1Val = EvaluateConstantChrecAtConstant(this,
2384 R1->getValue());
2385 if (Range.contains(R1Val)) {
2386 // The next iteration must be out of the range...
2387 Constant *NextVal =
2388 ConstantExpr::getAdd(R1->getValue(),
2389 ConstantInt::get(R1->getType(), 1));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002390
Chris Lattner53e677a2004-04-02 20:23:17 +00002391 R1Val = EvaluateConstantChrecAtConstant(this, NextVal);
2392 if (!Range.contains(R1Val))
2393 return SCEVUnknown::get(NextVal);
2394 return new SCEVCouldNotCompute(); // Something strange happened
2395 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002396
Chris Lattner53e677a2004-04-02 20:23:17 +00002397 // If R1 was not in the range, then it is a good return value. Make
2398 // sure that R1-1 WAS in the range though, just in case.
2399 Constant *NextVal =
2400 ConstantExpr::getSub(R1->getValue(),
2401 ConstantInt::get(R1->getType(), 1));
2402 R1Val = EvaluateConstantChrecAtConstant(this, NextVal);
2403 if (Range.contains(R1Val))
2404 return R1;
2405 return new SCEVCouldNotCompute(); // Something strange happened
2406 }
2407 }
2408 }
2409
2410 // Fallback, if this is a general polynomial, figure out the progression
2411 // through brute force: evaluate until we find an iteration that fails the
2412 // test. This is likely to be slow, but getting an accurate trip count is
2413 // incredibly important, we will be able to simplify the exit test a lot, and
2414 // we are almost guaranteed to get a trip count in this case.
2415 ConstantInt *TestVal = ConstantInt::get(getType(), 0);
2416 ConstantInt *One = ConstantInt::get(getType(), 1);
2417 ConstantInt *EndVal = TestVal; // Stop when we wrap around.
2418 do {
2419 ++NumBruteForceEvaluations;
2420 SCEVHandle Val = evaluateAtIteration(SCEVConstant::get(TestVal));
2421 if (!isa<SCEVConstant>(Val)) // This shouldn't happen.
2422 return new SCEVCouldNotCompute();
2423
2424 // Check to see if we found the value!
2425 if (!Range.contains(cast<SCEVConstant>(Val)->getValue()))
2426 return SCEVConstant::get(TestVal);
2427
2428 // Increment to test the next index.
2429 TestVal = cast<ConstantInt>(ConstantExpr::getAdd(TestVal, One));
2430 } while (TestVal != EndVal);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002431
Chris Lattner53e677a2004-04-02 20:23:17 +00002432 return new SCEVCouldNotCompute();
2433}
2434
2435
2436
2437//===----------------------------------------------------------------------===//
2438// ScalarEvolution Class Implementation
2439//===----------------------------------------------------------------------===//
2440
2441bool ScalarEvolution::runOnFunction(Function &F) {
2442 Impl = new ScalarEvolutionsImpl(F, getAnalysis<LoopInfo>());
2443 return false;
2444}
2445
2446void ScalarEvolution::releaseMemory() {
2447 delete (ScalarEvolutionsImpl*)Impl;
2448 Impl = 0;
2449}
2450
2451void ScalarEvolution::getAnalysisUsage(AnalysisUsage &AU) const {
2452 AU.setPreservesAll();
Chris Lattner53e677a2004-04-02 20:23:17 +00002453 AU.addRequiredTransitive<LoopInfo>();
2454}
2455
2456SCEVHandle ScalarEvolution::getSCEV(Value *V) const {
2457 return ((ScalarEvolutionsImpl*)Impl)->getSCEV(V);
2458}
2459
Chris Lattnera0740fb2005-08-09 23:36:33 +00002460/// hasSCEV - Return true if the SCEV for this value has already been
2461/// computed.
2462bool ScalarEvolution::hasSCEV(Value *V) const {
Chris Lattner05bd3742005-08-10 00:59:40 +00002463 return ((ScalarEvolutionsImpl*)Impl)->hasSCEV(V);
Chris Lattnera0740fb2005-08-09 23:36:33 +00002464}
2465
2466
2467/// setSCEV - Insert the specified SCEV into the map of current SCEVs for
2468/// the specified value.
2469void ScalarEvolution::setSCEV(Value *V, const SCEVHandle &H) {
2470 ((ScalarEvolutionsImpl*)Impl)->setSCEV(V, H);
2471}
2472
2473
Chris Lattner53e677a2004-04-02 20:23:17 +00002474SCEVHandle ScalarEvolution::getIterationCount(const Loop *L) const {
2475 return ((ScalarEvolutionsImpl*)Impl)->getIterationCount(L);
2476}
2477
2478bool ScalarEvolution::hasLoopInvariantIterationCount(const Loop *L) const {
2479 return !isa<SCEVCouldNotCompute>(getIterationCount(L));
2480}
2481
2482SCEVHandle ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) const {
2483 return ((ScalarEvolutionsImpl*)Impl)->getSCEVAtScope(getSCEV(V), L);
2484}
2485
2486void ScalarEvolution::deleteInstructionFromRecords(Instruction *I) const {
2487 return ((ScalarEvolutionsImpl*)Impl)->deleteInstructionFromRecords(I);
2488}
2489
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002490static void PrintLoopInfo(std::ostream &OS, const ScalarEvolution *SE,
Chris Lattner53e677a2004-04-02 20:23:17 +00002491 const Loop *L) {
2492 // Print all inner loops first
2493 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
2494 PrintLoopInfo(OS, SE, *I);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002495
Bill Wendling6f81b512006-11-28 22:46:12 +00002496 llvm_cerr << "Loop " << L->getHeader()->getName() << ": ";
Chris Lattnerf1ab4b42004-04-18 22:14:10 +00002497
2498 std::vector<BasicBlock*> ExitBlocks;
2499 L->getExitBlocks(ExitBlocks);
2500 if (ExitBlocks.size() != 1)
Bill Wendling6f81b512006-11-28 22:46:12 +00002501 llvm_cerr << "<multiple exits> ";
Chris Lattner53e677a2004-04-02 20:23:17 +00002502
2503 if (SE->hasLoopInvariantIterationCount(L)) {
Bill Wendling6f81b512006-11-28 22:46:12 +00002504 llvm_cerr << *SE->getIterationCount(L) << " iterations! ";
Chris Lattner53e677a2004-04-02 20:23:17 +00002505 } else {
Bill Wendling6f81b512006-11-28 22:46:12 +00002506 llvm_cerr << "Unpredictable iteration count. ";
Chris Lattner53e677a2004-04-02 20:23:17 +00002507 }
2508
Bill Wendling6f81b512006-11-28 22:46:12 +00002509 llvm_cerr << "\n";
Chris Lattner53e677a2004-04-02 20:23:17 +00002510}
2511
Reid Spencerce9653c2004-12-07 04:03:45 +00002512void ScalarEvolution::print(std::ostream &OS, const Module* ) const {
Chris Lattner53e677a2004-04-02 20:23:17 +00002513 Function &F = ((ScalarEvolutionsImpl*)Impl)->F;
2514 LoopInfo &LI = ((ScalarEvolutionsImpl*)Impl)->LI;
2515
2516 OS << "Classifying expressions for: " << F.getName() << "\n";
2517 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
Chris Lattner6ffe5512004-04-27 15:13:33 +00002518 if (I->getType()->isInteger()) {
2519 OS << *I;
Chris Lattner53e677a2004-04-02 20:23:17 +00002520 OS << " --> ";
Chris Lattner6ffe5512004-04-27 15:13:33 +00002521 SCEVHandle SV = getSCEV(&*I);
Chris Lattner53e677a2004-04-02 20:23:17 +00002522 SV->print(OS);
2523 OS << "\t\t";
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002524
Chris Lattner6ffe5512004-04-27 15:13:33 +00002525 if ((*I).getType()->isIntegral()) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002526 ConstantRange Bounds = SV->getValueRange();
2527 if (!Bounds.isFullSet())
2528 OS << "Bounds: " << Bounds << " ";
2529 }
2530
Chris Lattner6ffe5512004-04-27 15:13:33 +00002531 if (const Loop *L = LI.getLoopFor((*I).getParent())) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002532 OS << "Exits: ";
Chris Lattner6ffe5512004-04-27 15:13:33 +00002533 SCEVHandle ExitValue = getSCEVAtScope(&*I, L->getParentLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00002534 if (isa<SCEVCouldNotCompute>(ExitValue)) {
2535 OS << "<<Unknown>>";
2536 } else {
2537 OS << *ExitValue;
2538 }
2539 }
2540
2541
2542 OS << "\n";
2543 }
2544
2545 OS << "Determining loop execution counts for: " << F.getName() << "\n";
2546 for (LoopInfo::iterator I = LI.begin(), E = LI.end(); I != E; ++I)
2547 PrintLoopInfo(OS, this, *I);
2548}
2549