blob: 6cc89bd8019f3d4308418d1efa1ea13bd58eba59 [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"
Chris Lattner75de5ab2006-12-19 01:16:02 +000077#include "llvm/Support/MathExtras.h"
Bill Wendling6f81b512006-11-28 22:46:12 +000078#include "llvm/Support/Streams.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000079#include "llvm/ADT/Statistic.h"
Bill Wendling6f81b512006-11-28 22:46:12 +000080#include <ostream>
Alkis Evlogimenos20aa4742004-09-03 18:19:51 +000081#include <algorithm>
Jeff Cohen97af7512006-12-02 02:22:01 +000082#include <cmath>
Chris Lattner53e677a2004-04-02 20:23:17 +000083using namespace llvm;
84
85namespace {
Chris Lattner5d8925c2006-08-27 22:30:17 +000086 RegisterPass<ScalarEvolution>
Chris Lattner45a1cf82004-04-19 03:42:32 +000087 R("scalar-evolution", "Scalar Evolution Analysis");
Chris Lattner53e677a2004-04-02 20:23:17 +000088
Chris Lattnerac0b6ae2006-12-06 17:46:33 +000089 Statistic
Chris Lattner53e677a2004-04-02 20:23:17 +000090 NumBruteForceEvaluations("scalar-evolution",
Chris Lattner673e02b2004-10-12 01:49:27 +000091 "Number of brute force evaluations needed to "
92 "calculate high-order polynomial exit values");
Chris Lattnerac0b6ae2006-12-06 17:46:33 +000093 Statistic
Chris Lattner673e02b2004-10-12 01:49:27 +000094 NumArrayLenItCounts("scalar-evolution",
95 "Number of trip counts computed with array length");
Chris Lattnerac0b6ae2006-12-06 17:46:33 +000096 Statistic
Chris Lattner53e677a2004-04-02 20:23:17 +000097 NumTripCountsComputed("scalar-evolution",
98 "Number of loops with predictable loop counts");
Chris Lattnerac0b6ae2006-12-06 17:46:33 +000099 Statistic
Chris Lattner53e677a2004-04-02 20:23:17 +0000100 NumTripCountsNotComputed("scalar-evolution",
101 "Number of loops without predictable loop counts");
Chris Lattnerac0b6ae2006-12-06 17:46:33 +0000102 Statistic
Chris Lattner7980fb92004-04-17 18:36:24 +0000103 NumBruteForceTripCountsComputed("scalar-evolution",
104 "Number of loops with trip counts computed by force");
105
106 cl::opt<unsigned>
107 MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden,
Chris Lattnerbed21de2005-09-28 22:30:58 +0000108 cl::desc("Maximum number of iterations SCEV will "
109 "symbolically execute a constant derived loop"),
Chris Lattner7980fb92004-04-17 18:36:24 +0000110 cl::init(100));
Chris Lattner53e677a2004-04-02 20:23:17 +0000111}
112
113//===----------------------------------------------------------------------===//
114// SCEV class definitions
115//===----------------------------------------------------------------------===//
116
117//===----------------------------------------------------------------------===//
118// Implementation of the SCEV class.
119//
Chris Lattner53e677a2004-04-02 20:23:17 +0000120SCEV::~SCEV() {}
121void SCEV::dump() const {
Bill Wendlinge8156192006-12-07 01:30:32 +0000122 print(cerr);
Chris Lattner53e677a2004-04-02 20:23:17 +0000123}
124
125/// getValueRange - Return the tightest constant bounds that this value is
126/// known to have. This method is only valid on integer SCEV objects.
127ConstantRange SCEV::getValueRange() const {
128 const Type *Ty = getType();
129 assert(Ty->isInteger() && "Can't get range for a non-integer SCEV!");
130 Ty = Ty->getUnsignedVersion();
131 // Default to a full range if no better information is available.
132 return ConstantRange(getType());
133}
134
135
136SCEVCouldNotCompute::SCEVCouldNotCompute() : SCEV(scCouldNotCompute) {}
137
138bool SCEVCouldNotCompute::isLoopInvariant(const Loop *L) const {
139 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
Misha Brukmanbb2aff12004-04-05 19:00:46 +0000140 return false;
Chris Lattner53e677a2004-04-02 20:23:17 +0000141}
142
143const Type *SCEVCouldNotCompute::getType() const {
144 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
Misha Brukmanbb2aff12004-04-05 19:00:46 +0000145 return 0;
Chris Lattner53e677a2004-04-02 20:23:17 +0000146}
147
148bool SCEVCouldNotCompute::hasComputableLoopEvolution(const Loop *L) const {
149 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
150 return false;
151}
152
Chris Lattner4dc534c2005-02-13 04:37:18 +0000153SCEVHandle SCEVCouldNotCompute::
154replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
155 const SCEVHandle &Conc) const {
156 return this;
157}
158
Chris Lattner53e677a2004-04-02 20:23:17 +0000159void SCEVCouldNotCompute::print(std::ostream &OS) const {
160 OS << "***COULDNOTCOMPUTE***";
161}
162
163bool SCEVCouldNotCompute::classof(const SCEV *S) {
164 return S->getSCEVType() == scCouldNotCompute;
165}
166
167
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000168// SCEVConstants - Only allow the creation of one SCEVConstant for any
169// particular value. Don't use a SCEVHandle here, or else the object will
170// never be deleted!
Chris Lattnerb3364092006-10-04 21:49:37 +0000171static ManagedStatic<std::map<ConstantInt*, SCEVConstant*> > SCEVConstants;
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000172
Chris Lattner53e677a2004-04-02 20:23:17 +0000173
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000174SCEVConstant::~SCEVConstant() {
Chris Lattnerb3364092006-10-04 21:49:37 +0000175 SCEVConstants->erase(V);
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000176}
Chris Lattner53e677a2004-04-02 20:23:17 +0000177
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000178SCEVHandle SCEVConstant::get(ConstantInt *V) {
179 // Make sure that SCEVConstant instances are all unsigned.
180 if (V->getType()->isSigned()) {
181 const Type *NewTy = V->getType()->getUnsignedVersion();
Reid Spencer14bab5d2006-12-04 17:05:42 +0000182 V = cast<ConstantInt>(
Reid Spencer7858b332006-12-05 19:14:13 +0000183 ConstantExpr::getBitCast(V, NewTy));
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000184 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000185
Chris Lattnerb3364092006-10-04 21:49:37 +0000186 SCEVConstant *&R = (*SCEVConstants)[V];
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000187 if (R == 0) R = new SCEVConstant(V);
188 return R;
189}
Chris Lattner53e677a2004-04-02 20:23:17 +0000190
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000191ConstantRange SCEVConstant::getValueRange() const {
192 return ConstantRange(V);
193}
Chris Lattner53e677a2004-04-02 20:23:17 +0000194
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000195const Type *SCEVConstant::getType() const { return V->getType(); }
Chris Lattner53e677a2004-04-02 20:23:17 +0000196
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000197void SCEVConstant::print(std::ostream &OS) const {
198 WriteAsOperand(OS, V, false);
199}
Chris Lattner53e677a2004-04-02 20:23:17 +0000200
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000201// SCEVTruncates - Only allow the creation of one SCEVTruncateExpr for any
202// particular input. Don't use a SCEVHandle here, or else the object will
203// never be deleted!
Chris Lattnerb3364092006-10-04 21:49:37 +0000204static ManagedStatic<std::map<std::pair<SCEV*, const Type*>,
205 SCEVTruncateExpr*> > SCEVTruncates;
Chris Lattner53e677a2004-04-02 20:23:17 +0000206
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000207SCEVTruncateExpr::SCEVTruncateExpr(const SCEVHandle &op, const Type *ty)
208 : SCEV(scTruncate), Op(op), Ty(ty) {
209 assert(Op->getType()->isInteger() && Ty->isInteger() &&
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000210 "Cannot truncate non-integer value!");
211 assert(Op->getType()->getPrimitiveSize() > Ty->getPrimitiveSize() &&
212 "This is not a truncating conversion!");
213}
Chris Lattner53e677a2004-04-02 20:23:17 +0000214
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000215SCEVTruncateExpr::~SCEVTruncateExpr() {
Chris Lattnerb3364092006-10-04 21:49:37 +0000216 SCEVTruncates->erase(std::make_pair(Op, Ty));
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000217}
Chris Lattner53e677a2004-04-02 20:23:17 +0000218
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000219ConstantRange SCEVTruncateExpr::getValueRange() const {
220 return getOperand()->getValueRange().truncate(getType());
221}
Chris Lattner53e677a2004-04-02 20:23:17 +0000222
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000223void SCEVTruncateExpr::print(std::ostream &OS) const {
224 OS << "(truncate " << *Op << " to " << *Ty << ")";
225}
226
227// SCEVZeroExtends - Only allow the creation of one SCEVZeroExtendExpr for any
228// particular input. Don't use a SCEVHandle here, or else the object will never
229// be deleted!
Chris Lattnerb3364092006-10-04 21:49:37 +0000230static ManagedStatic<std::map<std::pair<SCEV*, const Type*>,
231 SCEVZeroExtendExpr*> > SCEVZeroExtends;
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000232
233SCEVZeroExtendExpr::SCEVZeroExtendExpr(const SCEVHandle &op, const Type *ty)
Reid Spencer48d8a702006-11-01 21:53:12 +0000234 : SCEV(scZeroExtend), Op(op), Ty(ty) {
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000235 assert(Op->getType()->isInteger() && Ty->isInteger() &&
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000236 "Cannot zero extend non-integer value!");
237 assert(Op->getType()->getPrimitiveSize() < Ty->getPrimitiveSize() &&
238 "This is not an extending conversion!");
239}
240
241SCEVZeroExtendExpr::~SCEVZeroExtendExpr() {
Chris Lattnerb3364092006-10-04 21:49:37 +0000242 SCEVZeroExtends->erase(std::make_pair(Op, Ty));
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000243}
244
245ConstantRange SCEVZeroExtendExpr::getValueRange() const {
246 return getOperand()->getValueRange().zeroExtend(getType());
247}
248
249void SCEVZeroExtendExpr::print(std::ostream &OS) const {
250 OS << "(zeroextend " << *Op << " to " << *Ty << ")";
251}
252
253// SCEVCommExprs - Only allow the creation of one SCEVCommutativeExpr for any
254// particular input. Don't use a SCEVHandle here, or else the object will never
255// be deleted!
Chris Lattnerb3364092006-10-04 21:49:37 +0000256static ManagedStatic<std::map<std::pair<unsigned, std::vector<SCEV*> >,
257 SCEVCommutativeExpr*> > SCEVCommExprs;
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000258
259SCEVCommutativeExpr::~SCEVCommutativeExpr() {
Chris Lattnerb3364092006-10-04 21:49:37 +0000260 SCEVCommExprs->erase(std::make_pair(getSCEVType(),
261 std::vector<SCEV*>(Operands.begin(),
262 Operands.end())));
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000263}
264
265void SCEVCommutativeExpr::print(std::ostream &OS) const {
266 assert(Operands.size() > 1 && "This plus expr shouldn't exist!");
267 const char *OpStr = getOperationStr();
268 OS << "(" << *Operands[0];
269 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
270 OS << OpStr << *Operands[i];
271 OS << ")";
272}
273
Chris Lattner4dc534c2005-02-13 04:37:18 +0000274SCEVHandle SCEVCommutativeExpr::
275replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
276 const SCEVHandle &Conc) const {
277 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
278 SCEVHandle H = getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc);
279 if (H != getOperand(i)) {
280 std::vector<SCEVHandle> NewOps;
281 NewOps.reserve(getNumOperands());
282 for (unsigned j = 0; j != i; ++j)
283 NewOps.push_back(getOperand(j));
284 NewOps.push_back(H);
285 for (++i; i != e; ++i)
286 NewOps.push_back(getOperand(i)->
287 replaceSymbolicValuesWithConcrete(Sym, Conc));
288
289 if (isa<SCEVAddExpr>(this))
290 return SCEVAddExpr::get(NewOps);
291 else if (isa<SCEVMulExpr>(this))
292 return SCEVMulExpr::get(NewOps);
293 else
294 assert(0 && "Unknown commutative expr!");
295 }
296 }
297 return this;
298}
299
300
Chris Lattner60a05cc2006-04-01 04:48:52 +0000301// SCEVSDivs - Only allow the creation of one SCEVSDivExpr for any particular
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000302// input. Don't use a SCEVHandle here, or else the object will never be
303// deleted!
Chris Lattnerb3364092006-10-04 21:49:37 +0000304static ManagedStatic<std::map<std::pair<SCEV*, SCEV*>,
305 SCEVSDivExpr*> > SCEVSDivs;
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000306
Chris Lattner60a05cc2006-04-01 04:48:52 +0000307SCEVSDivExpr::~SCEVSDivExpr() {
Chris Lattnerb3364092006-10-04 21:49:37 +0000308 SCEVSDivs->erase(std::make_pair(LHS, RHS));
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000309}
310
Chris Lattner60a05cc2006-04-01 04:48:52 +0000311void SCEVSDivExpr::print(std::ostream &OS) const {
312 OS << "(" << *LHS << " /s " << *RHS << ")";
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000313}
314
Chris Lattner60a05cc2006-04-01 04:48:52 +0000315const Type *SCEVSDivExpr::getType() const {
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000316 const Type *Ty = LHS->getType();
Chris Lattner60a05cc2006-04-01 04:48:52 +0000317 if (Ty->isUnsigned()) Ty = Ty->getSignedVersion();
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000318 return Ty;
319}
320
321// SCEVAddRecExprs - Only allow the creation of one SCEVAddRecExpr for any
322// particular input. Don't use a SCEVHandle here, or else the object will never
323// be deleted!
Chris Lattnerb3364092006-10-04 21:49:37 +0000324static ManagedStatic<std::map<std::pair<const Loop *, std::vector<SCEV*> >,
325 SCEVAddRecExpr*> > SCEVAddRecExprs;
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000326
327SCEVAddRecExpr::~SCEVAddRecExpr() {
Chris Lattnerb3364092006-10-04 21:49:37 +0000328 SCEVAddRecExprs->erase(std::make_pair(L,
329 std::vector<SCEV*>(Operands.begin(),
330 Operands.end())));
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000331}
332
Chris Lattner4dc534c2005-02-13 04:37:18 +0000333SCEVHandle SCEVAddRecExpr::
334replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
335 const SCEVHandle &Conc) const {
336 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
337 SCEVHandle H = getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc);
338 if (H != getOperand(i)) {
339 std::vector<SCEVHandle> NewOps;
340 NewOps.reserve(getNumOperands());
341 for (unsigned j = 0; j != i; ++j)
342 NewOps.push_back(getOperand(j));
343 NewOps.push_back(H);
344 for (++i; i != e; ++i)
345 NewOps.push_back(getOperand(i)->
346 replaceSymbolicValuesWithConcrete(Sym, Conc));
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000347
Chris Lattner4dc534c2005-02-13 04:37:18 +0000348 return get(NewOps, L);
349 }
350 }
351 return this;
352}
353
354
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000355bool SCEVAddRecExpr::isLoopInvariant(const Loop *QueryLoop) const {
356 // This recurrence is invariant w.r.t to QueryLoop iff QueryLoop doesn't
Chris Lattnerff2006a2005-08-16 00:37:01 +0000357 // contain L and if the start is invariant.
358 return !QueryLoop->contains(L->getHeader()) &&
359 getOperand(0)->isLoopInvariant(QueryLoop);
Chris Lattner53e677a2004-04-02 20:23:17 +0000360}
361
362
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000363void SCEVAddRecExpr::print(std::ostream &OS) const {
364 OS << "{" << *Operands[0];
365 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
366 OS << ",+," << *Operands[i];
367 OS << "}<" << L->getHeader()->getName() + ">";
368}
Chris Lattner53e677a2004-04-02 20:23:17 +0000369
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000370// SCEVUnknowns - Only allow the creation of one SCEVUnknown for any particular
371// value. Don't use a SCEVHandle here, or else the object will never be
372// deleted!
Chris Lattnerb3364092006-10-04 21:49:37 +0000373static ManagedStatic<std::map<Value*, SCEVUnknown*> > SCEVUnknowns;
Chris Lattner53e677a2004-04-02 20:23:17 +0000374
Chris Lattnerb3364092006-10-04 21:49:37 +0000375SCEVUnknown::~SCEVUnknown() { SCEVUnknowns->erase(V); }
Chris Lattner53e677a2004-04-02 20:23:17 +0000376
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000377bool SCEVUnknown::isLoopInvariant(const Loop *L) const {
378 // All non-instruction values are loop invariant. All instructions are loop
379 // invariant if they are not contained in the specified loop.
380 if (Instruction *I = dyn_cast<Instruction>(V))
381 return !L->contains(I->getParent());
382 return true;
383}
Chris Lattner53e677a2004-04-02 20:23:17 +0000384
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000385const Type *SCEVUnknown::getType() const {
386 return V->getType();
387}
Chris Lattner53e677a2004-04-02 20:23:17 +0000388
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000389void SCEVUnknown::print(std::ostream &OS) const {
390 WriteAsOperand(OS, V, false);
Chris Lattner53e677a2004-04-02 20:23:17 +0000391}
392
Chris Lattner8d741b82004-06-20 06:23:15 +0000393//===----------------------------------------------------------------------===//
394// SCEV Utilities
395//===----------------------------------------------------------------------===//
396
397namespace {
398 /// SCEVComplexityCompare - Return true if the complexity of the LHS is less
399 /// than the complexity of the RHS. This comparator is used to canonicalize
400 /// expressions.
Chris Lattner95255282006-06-28 23:17:24 +0000401 struct VISIBILITY_HIDDEN SCEVComplexityCompare {
Chris Lattner8d741b82004-06-20 06:23:15 +0000402 bool operator()(SCEV *LHS, SCEV *RHS) {
403 return LHS->getSCEVType() < RHS->getSCEVType();
404 }
405 };
406}
407
408/// GroupByComplexity - Given a list of SCEV objects, order them by their
409/// complexity, and group objects of the same complexity together by value.
410/// When this routine is finished, we know that any duplicates in the vector are
411/// consecutive and that complexity is monotonically increasing.
412///
413/// Note that we go take special precautions to ensure that we get determinstic
414/// results from this routine. In other words, we don't want the results of
415/// this to depend on where the addresses of various SCEV objects happened to
416/// land in memory.
417///
418static void GroupByComplexity(std::vector<SCEVHandle> &Ops) {
419 if (Ops.size() < 2) return; // Noop
420 if (Ops.size() == 2) {
421 // This is the common case, which also happens to be trivially simple.
422 // Special case it.
423 if (Ops[0]->getSCEVType() > Ops[1]->getSCEVType())
424 std::swap(Ops[0], Ops[1]);
425 return;
426 }
427
428 // Do the rough sort by complexity.
429 std::sort(Ops.begin(), Ops.end(), SCEVComplexityCompare());
430
431 // Now that we are sorted by complexity, group elements of the same
432 // complexity. Note that this is, at worst, N^2, but the vector is likely to
433 // be extremely short in practice. Note that we take this approach because we
434 // do not want to depend on the addresses of the objects we are grouping.
Chris Lattner2d584522004-06-20 17:01:44 +0000435 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
Chris Lattner8d741b82004-06-20 06:23:15 +0000436 SCEV *S = Ops[i];
437 unsigned Complexity = S->getSCEVType();
438
439 // If there are any objects of the same complexity and same value as this
440 // one, group them.
441 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
442 if (Ops[j] == S) { // Found a duplicate.
443 // Move it to immediately after i'th element.
444 std::swap(Ops[i+1], Ops[j]);
445 ++i; // no need to rescan it.
Chris Lattner541ad5e2004-06-20 20:32:16 +0000446 if (i == e-2) return; // Done!
Chris Lattner8d741b82004-06-20 06:23:15 +0000447 }
448 }
449 }
450}
451
Chris Lattner53e677a2004-04-02 20:23:17 +0000452
Chris Lattner53e677a2004-04-02 20:23:17 +0000453
454//===----------------------------------------------------------------------===//
455// Simple SCEV method implementations
456//===----------------------------------------------------------------------===//
457
458/// getIntegerSCEV - Given an integer or FP type, create a constant for the
459/// specified signed integer value and return a SCEV for the constant.
Chris Lattnerb06432c2004-04-23 21:29:03 +0000460SCEVHandle SCEVUnknown::getIntegerSCEV(int Val, const Type *Ty) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000461 Constant *C;
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000462 if (Val == 0)
Chris Lattner53e677a2004-04-02 20:23:17 +0000463 C = Constant::getNullValue(Ty);
464 else if (Ty->isFloatingPoint())
465 C = ConstantFP::get(Ty, Val);
466 else if (Ty->isSigned())
Reid Spencerb83eb642006-10-20 07:07:24 +0000467 C = ConstantInt::get(Ty, Val);
Chris Lattner53e677a2004-04-02 20:23:17 +0000468 else {
Reid Spencerb83eb642006-10-20 07:07:24 +0000469 C = ConstantInt::get(Ty->getSignedVersion(), Val);
Reid Spencer7858b332006-12-05 19:14:13 +0000470 C = ConstantExpr::getBitCast(C, Ty);
Chris Lattner53e677a2004-04-02 20:23:17 +0000471 }
472 return SCEVUnknown::get(C);
473}
474
475/// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion of the
476/// input value to the specified type. If the type must be extended, it is zero
477/// extended.
478static SCEVHandle getTruncateOrZeroExtend(const SCEVHandle &V, const Type *Ty) {
479 const Type *SrcTy = V->getType();
480 assert(SrcTy->isInteger() && Ty->isInteger() &&
481 "Cannot truncate or zero extend with non-integer arguments!");
482 if (SrcTy->getPrimitiveSize() == Ty->getPrimitiveSize())
483 return V; // No conversion
484 if (SrcTy->getPrimitiveSize() > Ty->getPrimitiveSize())
485 return SCEVTruncateExpr::get(V, Ty);
486 return SCEVZeroExtendExpr::get(V, Ty);
487}
488
489/// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V
490///
Chris Lattnerbac5b462005-03-09 05:34:41 +0000491SCEVHandle SCEV::getNegativeSCEV(const SCEVHandle &V) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000492 if (SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
493 return SCEVUnknown::get(ConstantExpr::getNeg(VC->getValue()));
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000494
Chris Lattnerb06432c2004-04-23 21:29:03 +0000495 return SCEVMulExpr::get(V, SCEVUnknown::getIntegerSCEV(-1, V->getType()));
Chris Lattner53e677a2004-04-02 20:23:17 +0000496}
497
498/// getMinusSCEV - Return a SCEV corresponding to LHS - RHS.
499///
Chris Lattnerbac5b462005-03-09 05:34:41 +0000500SCEVHandle SCEV::getMinusSCEV(const SCEVHandle &LHS, const SCEVHandle &RHS) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000501 // X - Y --> X + -Y
Chris Lattnerbac5b462005-03-09 05:34:41 +0000502 return SCEVAddExpr::get(LHS, SCEV::getNegativeSCEV(RHS));
Chris Lattner53e677a2004-04-02 20:23:17 +0000503}
504
505
Chris Lattner53e677a2004-04-02 20:23:17 +0000506/// PartialFact - Compute V!/(V-NumSteps)!
507static SCEVHandle PartialFact(SCEVHandle V, unsigned NumSteps) {
508 // Handle this case efficiently, it is common to have constant iteration
509 // counts while computing loop exit values.
510 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(V)) {
Reid Spencerb83eb642006-10-20 07:07:24 +0000511 uint64_t Val = SC->getValue()->getZExtValue();
Chris Lattner53e677a2004-04-02 20:23:17 +0000512 uint64_t Result = 1;
513 for (; NumSteps; --NumSteps)
514 Result *= Val-(NumSteps-1);
Reid Spencerb83eb642006-10-20 07:07:24 +0000515 Constant *Res = ConstantInt::get(Type::ULongTy, Result);
Reid Spencer14bab5d2006-12-04 17:05:42 +0000516 return SCEVUnknown::get(
Reid Spencer7858b332006-12-05 19:14:13 +0000517 ConstantExpr::getTruncOrBitCast(Res, V->getType()));
Chris Lattner53e677a2004-04-02 20:23:17 +0000518 }
519
520 const Type *Ty = V->getType();
521 if (NumSteps == 0)
Chris Lattnerb06432c2004-04-23 21:29:03 +0000522 return SCEVUnknown::getIntegerSCEV(1, Ty);
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000523
Chris Lattner53e677a2004-04-02 20:23:17 +0000524 SCEVHandle Result = V;
525 for (unsigned i = 1; i != NumSteps; ++i)
Chris Lattnerbac5b462005-03-09 05:34:41 +0000526 Result = SCEVMulExpr::get(Result, SCEV::getMinusSCEV(V,
Chris Lattnerb06432c2004-04-23 21:29:03 +0000527 SCEVUnknown::getIntegerSCEV(i, Ty)));
Chris Lattner53e677a2004-04-02 20:23:17 +0000528 return Result;
529}
530
531
532/// evaluateAtIteration - Return the value of this chain of recurrences at
533/// the specified iteration number. We can evaluate this recurrence by
534/// multiplying each element in the chain by the binomial coefficient
535/// corresponding to it. In other words, we can evaluate {A,+,B,+,C,+,D} as:
536///
537/// A*choose(It, 0) + B*choose(It, 1) + C*choose(It, 2) + D*choose(It, 3)
538///
539/// FIXME/VERIFY: I don't trust that this is correct in the face of overflow.
540/// Is the binomial equation safe using modular arithmetic??
541///
542SCEVHandle SCEVAddRecExpr::evaluateAtIteration(SCEVHandle It) const {
543 SCEVHandle Result = getStart();
544 int Divisor = 1;
545 const Type *Ty = It->getType();
546 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
547 SCEVHandle BC = PartialFact(It, i);
548 Divisor *= i;
Chris Lattner60a05cc2006-04-01 04:48:52 +0000549 SCEVHandle Val = SCEVSDivExpr::get(SCEVMulExpr::get(BC, getOperand(i)),
Chris Lattnerb06432c2004-04-23 21:29:03 +0000550 SCEVUnknown::getIntegerSCEV(Divisor,Ty));
Chris Lattner53e677a2004-04-02 20:23:17 +0000551 Result = SCEVAddExpr::get(Result, Val);
552 }
553 return Result;
554}
555
556
557//===----------------------------------------------------------------------===//
558// SCEV Expression folder implementations
559//===----------------------------------------------------------------------===//
560
561SCEVHandle SCEVTruncateExpr::get(const SCEVHandle &Op, const Type *Ty) {
562 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
Reid Spencer7858b332006-12-05 19:14:13 +0000563 return SCEVUnknown::get(
Reid Spencer315d0552006-12-05 22:39:58 +0000564 ConstantExpr::getTrunc(SC->getValue(), Ty));
Chris Lattner53e677a2004-04-02 20:23:17 +0000565
566 // If the input value is a chrec scev made out of constants, truncate
567 // all of the constants.
568 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
569 std::vector<SCEVHandle> Operands;
570 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
571 // FIXME: This should allow truncation of other expression types!
572 if (isa<SCEVConstant>(AddRec->getOperand(i)))
573 Operands.push_back(get(AddRec->getOperand(i), Ty));
574 else
575 break;
576 if (Operands.size() == AddRec->getNumOperands())
577 return SCEVAddRecExpr::get(Operands, AddRec->getLoop());
578 }
579
Chris Lattnerb3364092006-10-04 21:49:37 +0000580 SCEVTruncateExpr *&Result = (*SCEVTruncates)[std::make_pair(Op, Ty)];
Chris Lattner53e677a2004-04-02 20:23:17 +0000581 if (Result == 0) Result = new SCEVTruncateExpr(Op, Ty);
582 return Result;
583}
584
585SCEVHandle SCEVZeroExtendExpr::get(const SCEVHandle &Op, const Type *Ty) {
586 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
Reid Spencer7858b332006-12-05 19:14:13 +0000587 return SCEVUnknown::get(
Reid Spencerd977d862006-12-12 23:36:14 +0000588 ConstantExpr::getZExt(SC->getValue(), Ty));
Chris Lattner53e677a2004-04-02 20:23:17 +0000589
590 // FIXME: If the input value is a chrec scev, and we can prove that the value
591 // did not overflow the old, smaller, value, we can zero extend all of the
592 // operands (often constants). This would allow analysis of something like
593 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
594
Chris Lattnerb3364092006-10-04 21:49:37 +0000595 SCEVZeroExtendExpr *&Result = (*SCEVZeroExtends)[std::make_pair(Op, Ty)];
Chris Lattner53e677a2004-04-02 20:23:17 +0000596 if (Result == 0) Result = new SCEVZeroExtendExpr(Op, Ty);
597 return Result;
598}
599
600// get - Get a canonical add expression, or something simpler if possible.
601SCEVHandle SCEVAddExpr::get(std::vector<SCEVHandle> &Ops) {
602 assert(!Ops.empty() && "Cannot get empty add!");
Chris Lattner627018b2004-04-07 16:16:11 +0000603 if (Ops.size() == 1) return Ops[0];
Chris Lattner53e677a2004-04-02 20:23:17 +0000604
605 // Sort by complexity, this groups all similar expression types together.
Chris Lattner8d741b82004-06-20 06:23:15 +0000606 GroupByComplexity(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +0000607
608 // If there are any constants, fold them together.
609 unsigned Idx = 0;
610 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
611 ++Idx;
Chris Lattner627018b2004-04-07 16:16:11 +0000612 assert(Idx < Ops.size());
Chris Lattner53e677a2004-04-02 20:23:17 +0000613 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
614 // We found two constants, fold them together!
615 Constant *Fold = ConstantExpr::getAdd(LHSC->getValue(), RHSC->getValue());
616 if (ConstantInt *CI = dyn_cast<ConstantInt>(Fold)) {
617 Ops[0] = SCEVConstant::get(CI);
618 Ops.erase(Ops.begin()+1); // Erase the folded element
619 if (Ops.size() == 1) return Ops[0];
Chris Lattner7ffc07d2005-02-26 18:50:19 +0000620 LHSC = cast<SCEVConstant>(Ops[0]);
Chris Lattner53e677a2004-04-02 20:23:17 +0000621 } else {
622 // If we couldn't fold the expression, move to the next constant. Note
623 // that this is impossible to happen in practice because we always
624 // constant fold constant ints to constant ints.
625 ++Idx;
626 }
627 }
628
629 // If we are left with a constant zero being added, strip it off.
630 if (cast<SCEVConstant>(Ops[0])->getValue()->isNullValue()) {
631 Ops.erase(Ops.begin());
632 --Idx;
633 }
634 }
635
Chris Lattner627018b2004-04-07 16:16:11 +0000636 if (Ops.size() == 1) return Ops[0];
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000637
Chris Lattner53e677a2004-04-02 20:23:17 +0000638 // Okay, check to see if the same value occurs in the operand list twice. If
639 // so, merge them together into an multiply expression. Since we sorted the
640 // list, these values are required to be adjacent.
641 const Type *Ty = Ops[0]->getType();
642 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
643 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
644 // Found a match, merge the two values into a multiply, and add any
645 // remaining values to the result.
Chris Lattnerb06432c2004-04-23 21:29:03 +0000646 SCEVHandle Two = SCEVUnknown::getIntegerSCEV(2, Ty);
Chris Lattner53e677a2004-04-02 20:23:17 +0000647 SCEVHandle Mul = SCEVMulExpr::get(Ops[i], Two);
648 if (Ops.size() == 2)
649 return Mul;
650 Ops.erase(Ops.begin()+i, Ops.begin()+i+2);
651 Ops.push_back(Mul);
652 return SCEVAddExpr::get(Ops);
653 }
654
655 // Okay, now we know the first non-constant operand. If there are add
656 // operands they would be next.
657 if (Idx < Ops.size()) {
658 bool DeletedAdd = false;
659 while (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
660 // If we have an add, expand the add operands onto the end of the operands
661 // list.
662 Ops.insert(Ops.end(), Add->op_begin(), Add->op_end());
663 Ops.erase(Ops.begin()+Idx);
664 DeletedAdd = true;
665 }
666
667 // If we deleted at least one add, we added operands to the end of the list,
668 // and they are not necessarily sorted. Recurse to resort and resimplify
669 // any operands we just aquired.
670 if (DeletedAdd)
671 return get(Ops);
672 }
673
674 // Skip over the add expression until we get to a multiply.
675 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
676 ++Idx;
677
678 // If we are adding something to a multiply expression, make sure the
679 // something is not already an operand of the multiply. If so, merge it into
680 // the multiply.
681 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
682 SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
683 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
684 SCEV *MulOpSCEV = Mul->getOperand(MulOp);
685 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
Chris Lattner6a1a78a2004-12-04 20:54:32 +0000686 if (MulOpSCEV == Ops[AddOp] && !isa<SCEVConstant>(MulOpSCEV)) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000687 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
688 SCEVHandle InnerMul = Mul->getOperand(MulOp == 0);
689 if (Mul->getNumOperands() != 2) {
690 // If the multiply has more than two operands, we must get the
691 // Y*Z term.
692 std::vector<SCEVHandle> MulOps(Mul->op_begin(), Mul->op_end());
693 MulOps.erase(MulOps.begin()+MulOp);
694 InnerMul = SCEVMulExpr::get(MulOps);
695 }
Chris Lattnerb06432c2004-04-23 21:29:03 +0000696 SCEVHandle One = SCEVUnknown::getIntegerSCEV(1, Ty);
Chris Lattner53e677a2004-04-02 20:23:17 +0000697 SCEVHandle AddOne = SCEVAddExpr::get(InnerMul, One);
698 SCEVHandle OuterMul = SCEVMulExpr::get(AddOne, Ops[AddOp]);
699 if (Ops.size() == 2) return OuterMul;
700 if (AddOp < Idx) {
701 Ops.erase(Ops.begin()+AddOp);
702 Ops.erase(Ops.begin()+Idx-1);
703 } else {
704 Ops.erase(Ops.begin()+Idx);
705 Ops.erase(Ops.begin()+AddOp-1);
706 }
707 Ops.push_back(OuterMul);
708 return SCEVAddExpr::get(Ops);
709 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000710
Chris Lattner53e677a2004-04-02 20:23:17 +0000711 // Check this multiply against other multiplies being added together.
712 for (unsigned OtherMulIdx = Idx+1;
713 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
714 ++OtherMulIdx) {
715 SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
716 // If MulOp occurs in OtherMul, we can fold the two multiplies
717 // together.
718 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
719 OMulOp != e; ++OMulOp)
720 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
721 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
722 SCEVHandle InnerMul1 = Mul->getOperand(MulOp == 0);
723 if (Mul->getNumOperands() != 2) {
724 std::vector<SCEVHandle> MulOps(Mul->op_begin(), Mul->op_end());
725 MulOps.erase(MulOps.begin()+MulOp);
726 InnerMul1 = SCEVMulExpr::get(MulOps);
727 }
728 SCEVHandle InnerMul2 = OtherMul->getOperand(OMulOp == 0);
729 if (OtherMul->getNumOperands() != 2) {
730 std::vector<SCEVHandle> MulOps(OtherMul->op_begin(),
731 OtherMul->op_end());
732 MulOps.erase(MulOps.begin()+OMulOp);
733 InnerMul2 = SCEVMulExpr::get(MulOps);
734 }
735 SCEVHandle InnerMulSum = SCEVAddExpr::get(InnerMul1,InnerMul2);
736 SCEVHandle OuterMul = SCEVMulExpr::get(MulOpSCEV, InnerMulSum);
737 if (Ops.size() == 2) return OuterMul;
738 Ops.erase(Ops.begin()+Idx);
739 Ops.erase(Ops.begin()+OtherMulIdx-1);
740 Ops.push_back(OuterMul);
741 return SCEVAddExpr::get(Ops);
742 }
743 }
744 }
745 }
746
747 // If there are any add recurrences in the operands list, see if any other
748 // added values are loop invariant. If so, we can fold them into the
749 // recurrence.
750 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
751 ++Idx;
752
753 // Scan over all recurrences, trying to fold loop invariants into them.
754 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
755 // Scan all of the other operands to this add and add them to the vector if
756 // they are loop invariant w.r.t. the recurrence.
757 std::vector<SCEVHandle> LIOps;
758 SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
759 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
760 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
761 LIOps.push_back(Ops[i]);
762 Ops.erase(Ops.begin()+i);
763 --i; --e;
764 }
765
766 // If we found some loop invariants, fold them into the recurrence.
767 if (!LIOps.empty()) {
768 // NLI + LI + { Start,+,Step} --> NLI + { LI+Start,+,Step }
769 LIOps.push_back(AddRec->getStart());
770
771 std::vector<SCEVHandle> AddRecOps(AddRec->op_begin(), AddRec->op_end());
772 AddRecOps[0] = SCEVAddExpr::get(LIOps);
773
774 SCEVHandle NewRec = SCEVAddRecExpr::get(AddRecOps, AddRec->getLoop());
775 // If all of the other operands were loop invariant, we are done.
776 if (Ops.size() == 1) return NewRec;
777
778 // Otherwise, add the folded AddRec by the non-liv parts.
779 for (unsigned i = 0;; ++i)
780 if (Ops[i] == AddRec) {
781 Ops[i] = NewRec;
782 break;
783 }
784 return SCEVAddExpr::get(Ops);
785 }
786
787 // Okay, if there weren't any loop invariants to be folded, check to see if
788 // there are multiple AddRec's with the same loop induction variable being
789 // added together. If so, we can fold them.
790 for (unsigned OtherIdx = Idx+1;
791 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
792 if (OtherIdx != Idx) {
793 SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
794 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
795 // Other + {A,+,B} + {C,+,D} --> Other + {A+C,+,B+D}
796 std::vector<SCEVHandle> NewOps(AddRec->op_begin(), AddRec->op_end());
797 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); i != e; ++i) {
798 if (i >= NewOps.size()) {
799 NewOps.insert(NewOps.end(), OtherAddRec->op_begin()+i,
800 OtherAddRec->op_end());
801 break;
802 }
803 NewOps[i] = SCEVAddExpr::get(NewOps[i], OtherAddRec->getOperand(i));
804 }
805 SCEVHandle NewAddRec = SCEVAddRecExpr::get(NewOps, AddRec->getLoop());
806
807 if (Ops.size() == 2) return NewAddRec;
808
809 Ops.erase(Ops.begin()+Idx);
810 Ops.erase(Ops.begin()+OtherIdx-1);
811 Ops.push_back(NewAddRec);
812 return SCEVAddExpr::get(Ops);
813 }
814 }
815
816 // Otherwise couldn't fold anything into this recurrence. Move onto the
817 // next one.
818 }
819
820 // Okay, it looks like we really DO need an add expr. Check to see if we
821 // already have one, otherwise create a new one.
822 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
Chris Lattnerb3364092006-10-04 21:49:37 +0000823 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scAddExpr,
824 SCEVOps)];
Chris Lattner53e677a2004-04-02 20:23:17 +0000825 if (Result == 0) Result = new SCEVAddExpr(Ops);
826 return Result;
827}
828
829
830SCEVHandle SCEVMulExpr::get(std::vector<SCEVHandle> &Ops) {
831 assert(!Ops.empty() && "Cannot get empty mul!");
832
833 // Sort by complexity, this groups all similar expression types together.
Chris Lattner8d741b82004-06-20 06:23:15 +0000834 GroupByComplexity(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +0000835
836 // If there are any constants, fold them together.
837 unsigned Idx = 0;
838 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
839
840 // C1*(C2+V) -> C1*C2 + C1*V
841 if (Ops.size() == 2)
842 if (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
843 if (Add->getNumOperands() == 2 &&
844 isa<SCEVConstant>(Add->getOperand(0)))
845 return SCEVAddExpr::get(SCEVMulExpr::get(LHSC, Add->getOperand(0)),
846 SCEVMulExpr::get(LHSC, Add->getOperand(1)));
847
848
849 ++Idx;
850 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
851 // We found two constants, fold them together!
852 Constant *Fold = ConstantExpr::getMul(LHSC->getValue(), RHSC->getValue());
853 if (ConstantInt *CI = dyn_cast<ConstantInt>(Fold)) {
854 Ops[0] = SCEVConstant::get(CI);
855 Ops.erase(Ops.begin()+1); // Erase the folded element
856 if (Ops.size() == 1) return Ops[0];
Chris Lattner7ffc07d2005-02-26 18:50:19 +0000857 LHSC = cast<SCEVConstant>(Ops[0]);
Chris Lattner53e677a2004-04-02 20:23:17 +0000858 } else {
859 // If we couldn't fold the expression, move to the next constant. Note
860 // that this is impossible to happen in practice because we always
861 // constant fold constant ints to constant ints.
862 ++Idx;
863 }
864 }
865
866 // If we are left with a constant one being multiplied, strip it off.
867 if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) {
868 Ops.erase(Ops.begin());
869 --Idx;
870 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isNullValue()) {
871 // If we have a multiply of zero, it will always be zero.
872 return Ops[0];
873 }
874 }
875
876 // Skip over the add expression until we get to a multiply.
877 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
878 ++Idx;
879
880 if (Ops.size() == 1)
881 return Ops[0];
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000882
Chris Lattner53e677a2004-04-02 20:23:17 +0000883 // If there are mul operands inline them all into this expression.
884 if (Idx < Ops.size()) {
885 bool DeletedMul = false;
886 while (SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
887 // If we have an mul, expand the mul operands onto the end of the operands
888 // list.
889 Ops.insert(Ops.end(), Mul->op_begin(), Mul->op_end());
890 Ops.erase(Ops.begin()+Idx);
891 DeletedMul = true;
892 }
893
894 // If we deleted at least one mul, we added operands to the end of the list,
895 // and they are not necessarily sorted. Recurse to resort and resimplify
896 // any operands we just aquired.
897 if (DeletedMul)
898 return get(Ops);
899 }
900
901 // If there are any add recurrences in the operands list, see if any other
902 // added values are loop invariant. If so, we can fold them into the
903 // recurrence.
904 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
905 ++Idx;
906
907 // Scan over all recurrences, trying to fold loop invariants into them.
908 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
909 // Scan all of the other operands to this mul and add them to the vector if
910 // they are loop invariant w.r.t. the recurrence.
911 std::vector<SCEVHandle> LIOps;
912 SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
913 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
914 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
915 LIOps.push_back(Ops[i]);
916 Ops.erase(Ops.begin()+i);
917 --i; --e;
918 }
919
920 // If we found some loop invariants, fold them into the recurrence.
921 if (!LIOps.empty()) {
922 // NLI * LI * { Start,+,Step} --> NLI * { LI*Start,+,LI*Step }
923 std::vector<SCEVHandle> NewOps;
924 NewOps.reserve(AddRec->getNumOperands());
925 if (LIOps.size() == 1) {
926 SCEV *Scale = LIOps[0];
927 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
928 NewOps.push_back(SCEVMulExpr::get(Scale, AddRec->getOperand(i)));
929 } else {
930 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
931 std::vector<SCEVHandle> MulOps(LIOps);
932 MulOps.push_back(AddRec->getOperand(i));
933 NewOps.push_back(SCEVMulExpr::get(MulOps));
934 }
935 }
936
937 SCEVHandle NewRec = SCEVAddRecExpr::get(NewOps, AddRec->getLoop());
938
939 // If all of the other operands were loop invariant, we are done.
940 if (Ops.size() == 1) return NewRec;
941
942 // Otherwise, multiply the folded AddRec by the non-liv parts.
943 for (unsigned i = 0;; ++i)
944 if (Ops[i] == AddRec) {
945 Ops[i] = NewRec;
946 break;
947 }
948 return SCEVMulExpr::get(Ops);
949 }
950
951 // Okay, if there weren't any loop invariants to be folded, check to see if
952 // there are multiple AddRec's with the same loop induction variable being
953 // multiplied together. If so, we can fold them.
954 for (unsigned OtherIdx = Idx+1;
955 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
956 if (OtherIdx != Idx) {
957 SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
958 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
959 // F * G --> {A,+,B} * {C,+,D} --> {A*C,+,F*D + G*B + B*D}
960 SCEVAddRecExpr *F = AddRec, *G = OtherAddRec;
961 SCEVHandle NewStart = SCEVMulExpr::get(F->getStart(),
962 G->getStart());
963 SCEVHandle B = F->getStepRecurrence();
964 SCEVHandle D = G->getStepRecurrence();
965 SCEVHandle NewStep = SCEVAddExpr::get(SCEVMulExpr::get(F, D),
966 SCEVMulExpr::get(G, B),
967 SCEVMulExpr::get(B, D));
968 SCEVHandle NewAddRec = SCEVAddRecExpr::get(NewStart, NewStep,
969 F->getLoop());
970 if (Ops.size() == 2) return NewAddRec;
971
972 Ops.erase(Ops.begin()+Idx);
973 Ops.erase(Ops.begin()+OtherIdx-1);
974 Ops.push_back(NewAddRec);
975 return SCEVMulExpr::get(Ops);
976 }
977 }
978
979 // Otherwise couldn't fold anything into this recurrence. Move onto the
980 // next one.
981 }
982
983 // Okay, it looks like we really DO need an mul expr. Check to see if we
984 // already have one, otherwise create a new one.
985 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
Chris Lattnerb3364092006-10-04 21:49:37 +0000986 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scMulExpr,
987 SCEVOps)];
Chris Lattner6a1a78a2004-12-04 20:54:32 +0000988 if (Result == 0)
989 Result = new SCEVMulExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +0000990 return Result;
991}
992
Chris Lattner60a05cc2006-04-01 04:48:52 +0000993SCEVHandle SCEVSDivExpr::get(const SCEVHandle &LHS, const SCEVHandle &RHS) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000994 if (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
995 if (RHSC->getValue()->equalsInt(1))
Reid Spencer1628cec2006-10-26 06:15:43 +0000996 return LHS; // X sdiv 1 --> x
Chris Lattner53e677a2004-04-02 20:23:17 +0000997 if (RHSC->getValue()->isAllOnesValue())
Reid Spencer1628cec2006-10-26 06:15:43 +0000998 return SCEV::getNegativeSCEV(LHS); // X sdiv -1 --> -x
Chris Lattner53e677a2004-04-02 20:23:17 +0000999
1000 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
1001 Constant *LHSCV = LHSC->getValue();
1002 Constant *RHSCV = RHSC->getValue();
Reid Spencer1628cec2006-10-26 06:15:43 +00001003 return SCEVUnknown::get(ConstantExpr::getSDiv(LHSCV, RHSCV));
Chris Lattner53e677a2004-04-02 20:23:17 +00001004 }
1005 }
1006
1007 // FIXME: implement folding of (X*4)/4 when we know X*4 doesn't overflow.
1008
Chris Lattnerb3364092006-10-04 21:49:37 +00001009 SCEVSDivExpr *&Result = (*SCEVSDivs)[std::make_pair(LHS, RHS)];
Chris Lattner60a05cc2006-04-01 04:48:52 +00001010 if (Result == 0) Result = new SCEVSDivExpr(LHS, RHS);
Chris Lattner53e677a2004-04-02 20:23:17 +00001011 return Result;
1012}
1013
1014
1015/// SCEVAddRecExpr::get - Get a add recurrence expression for the
1016/// specified loop. Simplify the expression as much as possible.
1017SCEVHandle SCEVAddRecExpr::get(const SCEVHandle &Start,
1018 const SCEVHandle &Step, const Loop *L) {
1019 std::vector<SCEVHandle> Operands;
1020 Operands.push_back(Start);
1021 if (SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
1022 if (StepChrec->getLoop() == L) {
1023 Operands.insert(Operands.end(), StepChrec->op_begin(),
1024 StepChrec->op_end());
1025 return get(Operands, L);
1026 }
1027
1028 Operands.push_back(Step);
1029 return get(Operands, L);
1030}
1031
1032/// SCEVAddRecExpr::get - Get a add recurrence expression for the
1033/// specified loop. Simplify the expression as much as possible.
1034SCEVHandle SCEVAddRecExpr::get(std::vector<SCEVHandle> &Operands,
1035 const Loop *L) {
1036 if (Operands.size() == 1) return Operands[0];
1037
1038 if (SCEVConstant *StepC = dyn_cast<SCEVConstant>(Operands.back()))
1039 if (StepC->getValue()->isNullValue()) {
1040 Operands.pop_back();
1041 return get(Operands, L); // { X,+,0 } --> X
1042 }
1043
1044 SCEVAddRecExpr *&Result =
Chris Lattnerb3364092006-10-04 21:49:37 +00001045 (*SCEVAddRecExprs)[std::make_pair(L, std::vector<SCEV*>(Operands.begin(),
1046 Operands.end()))];
Chris Lattner53e677a2004-04-02 20:23:17 +00001047 if (Result == 0) Result = new SCEVAddRecExpr(Operands, L);
1048 return Result;
1049}
1050
Chris Lattner0a7f98c2004-04-15 15:07:24 +00001051SCEVHandle SCEVUnknown::get(Value *V) {
1052 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
1053 return SCEVConstant::get(CI);
Chris Lattnerb3364092006-10-04 21:49:37 +00001054 SCEVUnknown *&Result = (*SCEVUnknowns)[V];
Chris Lattner0a7f98c2004-04-15 15:07:24 +00001055 if (Result == 0) Result = new SCEVUnknown(V);
1056 return Result;
1057}
1058
Chris Lattner53e677a2004-04-02 20:23:17 +00001059
1060//===----------------------------------------------------------------------===//
Chris Lattner53e677a2004-04-02 20:23:17 +00001061// ScalarEvolutionsImpl Definition and Implementation
1062//===----------------------------------------------------------------------===//
1063//
1064/// ScalarEvolutionsImpl - This class implements the main driver for the scalar
1065/// evolution code.
1066///
1067namespace {
Chris Lattner95255282006-06-28 23:17:24 +00001068 struct VISIBILITY_HIDDEN ScalarEvolutionsImpl {
Chris Lattner53e677a2004-04-02 20:23:17 +00001069 /// F - The function we are analyzing.
1070 ///
1071 Function &F;
1072
1073 /// LI - The loop information for the function we are currently analyzing.
1074 ///
1075 LoopInfo &LI;
1076
1077 /// UnknownValue - This SCEV is used to represent unknown trip counts and
1078 /// things.
1079 SCEVHandle UnknownValue;
1080
1081 /// Scalars - This is a cache of the scalars we have analyzed so far.
1082 ///
1083 std::map<Value*, SCEVHandle> Scalars;
1084
1085 /// IterationCounts - Cache the iteration count of the loops for this
1086 /// function as they are computed.
1087 std::map<const Loop*, SCEVHandle> IterationCounts;
1088
Chris Lattner3221ad02004-04-17 22:58:41 +00001089 /// ConstantEvolutionLoopExitValue - This map contains entries for all of
1090 /// the PHI instructions that we attempt to compute constant evolutions for.
1091 /// This allows us to avoid potentially expensive recomputation of these
1092 /// properties. An instruction maps to null if we are unable to compute its
1093 /// exit value.
1094 std::map<PHINode*, Constant*> ConstantEvolutionLoopExitValue;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001095
Chris Lattner53e677a2004-04-02 20:23:17 +00001096 public:
1097 ScalarEvolutionsImpl(Function &f, LoopInfo &li)
1098 : F(f), LI(li), UnknownValue(new SCEVCouldNotCompute()) {}
1099
1100 /// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
1101 /// expression and create a new one.
1102 SCEVHandle getSCEV(Value *V);
1103
Chris Lattnera0740fb2005-08-09 23:36:33 +00001104 /// hasSCEV - Return true if the SCEV for this value has already been
1105 /// computed.
1106 bool hasSCEV(Value *V) const {
1107 return Scalars.count(V);
1108 }
1109
1110 /// setSCEV - Insert the specified SCEV into the map of current SCEVs for
1111 /// the specified value.
1112 void setSCEV(Value *V, const SCEVHandle &H) {
1113 bool isNew = Scalars.insert(std::make_pair(V, H)).second;
1114 assert(isNew && "This entry already existed!");
1115 }
1116
1117
Chris Lattner53e677a2004-04-02 20:23:17 +00001118 /// getSCEVAtScope - Compute the value of the specified expression within
1119 /// the indicated loop (which may be null to indicate in no loop). If the
1120 /// expression cannot be evaluated, return UnknownValue itself.
1121 SCEVHandle getSCEVAtScope(SCEV *V, const Loop *L);
1122
1123
1124 /// hasLoopInvariantIterationCount - Return true if the specified loop has
1125 /// an analyzable loop-invariant iteration count.
1126 bool hasLoopInvariantIterationCount(const Loop *L);
1127
1128 /// getIterationCount - If the specified loop has a predictable iteration
1129 /// count, return it. Note that it is not valid to call this method on a
1130 /// loop without a loop-invariant iteration count.
1131 SCEVHandle getIterationCount(const Loop *L);
1132
1133 /// deleteInstructionFromRecords - This method should be called by the
1134 /// client before it removes an instruction from the program, to make sure
1135 /// that no dangling references are left around.
1136 void deleteInstructionFromRecords(Instruction *I);
1137
1138 private:
1139 /// createSCEV - We know that there is no SCEV for the specified value.
1140 /// Analyze the expression.
1141 SCEVHandle createSCEV(Value *V);
Chris Lattner53e677a2004-04-02 20:23:17 +00001142
1143 /// createNodeForPHI - Provide the special handling we need to analyze PHI
1144 /// SCEVs.
1145 SCEVHandle createNodeForPHI(PHINode *PN);
Chris Lattner4dc534c2005-02-13 04:37:18 +00001146
1147 /// ReplaceSymbolicValueWithConcrete - This looks up the computed SCEV value
1148 /// for the specified instruction and replaces any references to the
1149 /// symbolic value SymName with the specified value. This is used during
1150 /// PHI resolution.
1151 void ReplaceSymbolicValueWithConcrete(Instruction *I,
1152 const SCEVHandle &SymName,
1153 const SCEVHandle &NewVal);
Chris Lattner53e677a2004-04-02 20:23:17 +00001154
1155 /// ComputeIterationCount - Compute the number of times the specified loop
1156 /// will iterate.
1157 SCEVHandle ComputeIterationCount(const Loop *L);
1158
Chris Lattner673e02b2004-10-12 01:49:27 +00001159 /// ComputeLoadConstantCompareIterationCount - Given an exit condition of
1160 /// 'setcc load X, cst', try to se if we can compute the trip count.
1161 SCEVHandle ComputeLoadConstantCompareIterationCount(LoadInst *LI,
1162 Constant *RHS,
1163 const Loop *L,
1164 unsigned SetCCOpcode);
1165
Chris Lattner7980fb92004-04-17 18:36:24 +00001166 /// ComputeIterationCountExhaustively - If the trip is known to execute a
1167 /// constant number of times (the condition evolves only from constants),
1168 /// try to evaluate a few iterations of the loop until we get the exit
1169 /// condition gets a value of ExitWhen (true or false). If we cannot
1170 /// evaluate the trip count of the loop, return UnknownValue.
1171 SCEVHandle ComputeIterationCountExhaustively(const Loop *L, Value *Cond,
1172 bool ExitWhen);
1173
Chris Lattner53e677a2004-04-02 20:23:17 +00001174 /// HowFarToZero - Return the number of times a backedge comparing the
1175 /// specified value to zero will execute. If not computable, return
Chris Lattnerdb25de42005-08-15 23:33:51 +00001176 /// UnknownValue.
Chris Lattner53e677a2004-04-02 20:23:17 +00001177 SCEVHandle HowFarToZero(SCEV *V, const Loop *L);
1178
1179 /// HowFarToNonZero - Return the number of times a backedge checking the
1180 /// specified value for nonzero will execute. If not computable, return
Chris Lattnerdb25de42005-08-15 23:33:51 +00001181 /// UnknownValue.
Chris Lattner53e677a2004-04-02 20:23:17 +00001182 SCEVHandle HowFarToNonZero(SCEV *V, const Loop *L);
Chris Lattner3221ad02004-04-17 22:58:41 +00001183
Chris Lattnerdb25de42005-08-15 23:33:51 +00001184 /// HowManyLessThans - Return the number of times a backedge containing the
1185 /// specified less-than comparison will execute. If not computable, return
1186 /// UnknownValue.
1187 SCEVHandle HowManyLessThans(SCEV *LHS, SCEV *RHS, const Loop *L);
1188
Chris Lattner3221ad02004-04-17 22:58:41 +00001189 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
1190 /// in the header of its containing loop, we know the loop executes a
1191 /// constant number of times, and the PHI node is just a recurrence
1192 /// involving constants, fold it.
1193 Constant *getConstantEvolutionLoopExitValue(PHINode *PN, uint64_t Its,
1194 const Loop *L);
Chris Lattner53e677a2004-04-02 20:23:17 +00001195 };
1196}
1197
1198//===----------------------------------------------------------------------===//
1199// Basic SCEV Analysis and PHI Idiom Recognition Code
1200//
1201
1202/// deleteInstructionFromRecords - This method should be called by the
1203/// client before it removes an instruction from the program, to make sure
1204/// that no dangling references are left around.
1205void ScalarEvolutionsImpl::deleteInstructionFromRecords(Instruction *I) {
1206 Scalars.erase(I);
Chris Lattner3221ad02004-04-17 22:58:41 +00001207 if (PHINode *PN = dyn_cast<PHINode>(I))
1208 ConstantEvolutionLoopExitValue.erase(PN);
Chris Lattner53e677a2004-04-02 20:23:17 +00001209}
1210
1211
1212/// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
1213/// expression and create a new one.
1214SCEVHandle ScalarEvolutionsImpl::getSCEV(Value *V) {
1215 assert(V->getType() != Type::VoidTy && "Can't analyze void expressions!");
1216
1217 std::map<Value*, SCEVHandle>::iterator I = Scalars.find(V);
1218 if (I != Scalars.end()) return I->second;
1219 SCEVHandle S = createSCEV(V);
1220 Scalars.insert(std::make_pair(V, S));
1221 return S;
1222}
1223
Chris Lattner4dc534c2005-02-13 04:37:18 +00001224/// ReplaceSymbolicValueWithConcrete - This looks up the computed SCEV value for
1225/// the specified instruction and replaces any references to the symbolic value
1226/// SymName with the specified value. This is used during PHI resolution.
1227void ScalarEvolutionsImpl::
1228ReplaceSymbolicValueWithConcrete(Instruction *I, const SCEVHandle &SymName,
1229 const SCEVHandle &NewVal) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001230 std::map<Value*, SCEVHandle>::iterator SI = Scalars.find(I);
Chris Lattner4dc534c2005-02-13 04:37:18 +00001231 if (SI == Scalars.end()) return;
Chris Lattner53e677a2004-04-02 20:23:17 +00001232
Chris Lattner4dc534c2005-02-13 04:37:18 +00001233 SCEVHandle NV =
1234 SI->second->replaceSymbolicValuesWithConcrete(SymName, NewVal);
1235 if (NV == SI->second) return; // No change.
1236
1237 SI->second = NV; // Update the scalars map!
1238
1239 // Any instruction values that use this instruction might also need to be
1240 // updated!
1241 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1242 UI != E; ++UI)
1243 ReplaceSymbolicValueWithConcrete(cast<Instruction>(*UI), SymName, NewVal);
1244}
Chris Lattner53e677a2004-04-02 20:23:17 +00001245
1246/// createNodeForPHI - PHI nodes have two cases. Either the PHI node exists in
1247/// a loop header, making it a potential recurrence, or it doesn't.
1248///
1249SCEVHandle ScalarEvolutionsImpl::createNodeForPHI(PHINode *PN) {
1250 if (PN->getNumIncomingValues() == 2) // The loops have been canonicalized.
1251 if (const Loop *L = LI.getLoopFor(PN->getParent()))
1252 if (L->getHeader() == PN->getParent()) {
1253 // If it lives in the loop header, it has two incoming values, one
1254 // from outside the loop, and one from inside.
1255 unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0));
1256 unsigned BackEdge = IncomingEdge^1;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001257
Chris Lattner53e677a2004-04-02 20:23:17 +00001258 // While we are analyzing this PHI node, handle its value symbolically.
1259 SCEVHandle SymbolicName = SCEVUnknown::get(PN);
1260 assert(Scalars.find(PN) == Scalars.end() &&
1261 "PHI node already processed?");
1262 Scalars.insert(std::make_pair(PN, SymbolicName));
1263
1264 // Using this symbolic name for the PHI, analyze the value coming around
1265 // the back-edge.
1266 SCEVHandle BEValue = getSCEV(PN->getIncomingValue(BackEdge));
1267
1268 // NOTE: If BEValue is loop invariant, we know that the PHI node just
1269 // has a special value for the first iteration of the loop.
1270
1271 // If the value coming around the backedge is an add with the symbolic
1272 // value we just inserted, then we found a simple induction variable!
1273 if (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
1274 // If there is a single occurrence of the symbolic value, replace it
1275 // with a recurrence.
1276 unsigned FoundIndex = Add->getNumOperands();
1277 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
1278 if (Add->getOperand(i) == SymbolicName)
1279 if (FoundIndex == e) {
1280 FoundIndex = i;
1281 break;
1282 }
1283
1284 if (FoundIndex != Add->getNumOperands()) {
1285 // Create an add with everything but the specified operand.
1286 std::vector<SCEVHandle> Ops;
1287 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
1288 if (i != FoundIndex)
1289 Ops.push_back(Add->getOperand(i));
1290 SCEVHandle Accum = SCEVAddExpr::get(Ops);
1291
1292 // This is not a valid addrec if the step amount is varying each
1293 // loop iteration, but is not itself an addrec in this loop.
1294 if (Accum->isLoopInvariant(L) ||
1295 (isa<SCEVAddRecExpr>(Accum) &&
1296 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
1297 SCEVHandle StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
1298 SCEVHandle PHISCEV = SCEVAddRecExpr::get(StartVal, Accum, L);
1299
1300 // Okay, for the entire analysis of this edge we assumed the PHI
1301 // to be symbolic. We now need to go back and update all of the
1302 // entries for the scalars that use the PHI (except for the PHI
1303 // itself) to use the new analyzed value instead of the "symbolic"
1304 // value.
Chris Lattner4dc534c2005-02-13 04:37:18 +00001305 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
Chris Lattner53e677a2004-04-02 20:23:17 +00001306 return PHISCEV;
1307 }
1308 }
Chris Lattner97156e72006-04-26 18:34:07 +00001309 } else if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(BEValue)) {
1310 // Otherwise, this could be a loop like this:
1311 // i = 0; for (j = 1; ..; ++j) { .... i = j; }
1312 // In this case, j = {1,+,1} and BEValue is j.
1313 // Because the other in-value of i (0) fits the evolution of BEValue
1314 // i really is an addrec evolution.
1315 if (AddRec->getLoop() == L && AddRec->isAffine()) {
1316 SCEVHandle StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
1317
1318 // If StartVal = j.start - j.stride, we can use StartVal as the
1319 // initial step of the addrec evolution.
1320 if (StartVal == SCEV::getMinusSCEV(AddRec->getOperand(0),
1321 AddRec->getOperand(1))) {
1322 SCEVHandle PHISCEV =
1323 SCEVAddRecExpr::get(StartVal, AddRec->getOperand(1), L);
1324
1325 // Okay, for the entire analysis of this edge we assumed the PHI
1326 // to be symbolic. We now need to go back and update all of the
1327 // entries for the scalars that use the PHI (except for the PHI
1328 // itself) to use the new analyzed value instead of the "symbolic"
1329 // value.
1330 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
1331 return PHISCEV;
1332 }
1333 }
Chris Lattner53e677a2004-04-02 20:23:17 +00001334 }
1335
1336 return SymbolicName;
1337 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001338
Chris Lattner53e677a2004-04-02 20:23:17 +00001339 // If it's not a loop phi, we can't handle it yet.
1340 return SCEVUnknown::get(PN);
1341}
1342
Chris Lattnera17f0392006-12-12 02:26:09 +00001343/// GetConstantFactor - Determine the largest constant factor that S has. For
1344/// example, turn {4,+,8} -> 4. (S umod result) should always equal zero.
1345static uint64_t GetConstantFactor(SCEVHandle S) {
1346 if (SCEVConstant *C = dyn_cast<SCEVConstant>(S)) {
1347 if (uint64_t V = C->getValue()->getZExtValue())
1348 return V;
1349 else // Zero is a multiple of everything.
1350 return 1ULL << (S->getType()->getPrimitiveSizeInBits()-1);
1351 }
1352
1353 if (SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
1354 return GetConstantFactor(T->getOperand()) &
1355 T->getType()->getIntegralTypeMask();
1356 if (SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S))
1357 return GetConstantFactor(E->getOperand());
1358
1359 if (SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
1360 // The result is the min of all operands.
1361 uint64_t Res = GetConstantFactor(A->getOperand(0));
1362 for (unsigned i = 1, e = A->getNumOperands(); i != e && Res > 1; ++i)
1363 Res = std::min(Res, GetConstantFactor(A->getOperand(i)));
1364 return Res;
1365 }
1366
1367 if (SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
1368 // The result is the product of all the operands.
1369 uint64_t Res = GetConstantFactor(M->getOperand(0));
1370 for (unsigned i = 1, e = M->getNumOperands(); i != e; ++i)
1371 Res *= GetConstantFactor(M->getOperand(i));
1372 return Res;
1373 }
1374
1375 if (SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
Chris Lattner75de5ab2006-12-19 01:16:02 +00001376 // For now, we just handle linear expressions.
1377 if (A->getNumOperands() == 2) {
1378 // We want the GCD between the start and the stride value.
1379 uint64_t Start = GetConstantFactor(A->getOperand(0));
1380 if (Start == 1) return 1;
1381 uint64_t Stride = GetConstantFactor(A->getOperand(1));
1382 return GreatestCommonDivisor64(Start, Stride);
1383 }
Chris Lattnera17f0392006-12-12 02:26:09 +00001384 }
1385
1386 // SCEVSDivExpr, SCEVUnknown.
1387 return 1;
1388}
Chris Lattner53e677a2004-04-02 20:23:17 +00001389
1390/// createSCEV - We know that there is no SCEV for the specified value.
1391/// Analyze the expression.
1392///
1393SCEVHandle ScalarEvolutionsImpl::createSCEV(Value *V) {
1394 if (Instruction *I = dyn_cast<Instruction>(V)) {
1395 switch (I->getOpcode()) {
1396 case Instruction::Add:
1397 return SCEVAddExpr::get(getSCEV(I->getOperand(0)),
1398 getSCEV(I->getOperand(1)));
1399 case Instruction::Mul:
1400 return SCEVMulExpr::get(getSCEV(I->getOperand(0)),
1401 getSCEV(I->getOperand(1)));
Reid Spencer1628cec2006-10-26 06:15:43 +00001402 case Instruction::SDiv:
1403 return SCEVSDivExpr::get(getSCEV(I->getOperand(0)),
1404 getSCEV(I->getOperand(1)));
Chris Lattner53e677a2004-04-02 20:23:17 +00001405 break;
1406
1407 case Instruction::Sub:
Chris Lattnerbac5b462005-03-09 05:34:41 +00001408 return SCEV::getMinusSCEV(getSCEV(I->getOperand(0)),
1409 getSCEV(I->getOperand(1)));
Chris Lattnera17f0392006-12-12 02:26:09 +00001410 case Instruction::Or:
1411 // If the RHS of the Or is a constant, we may have something like:
1412 // X*4+1 which got turned into X*4|1. Handle this as an add so loop
1413 // optimizations will transparently handle this case.
1414 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
1415 SCEVHandle LHS = getSCEV(I->getOperand(0));
1416 uint64_t CommonFact = GetConstantFactor(LHS);
1417 assert(CommonFact && "Common factor should at least be 1!");
1418 if (CommonFact > CI->getZExtValue()) {
1419 // If the LHS is a multiple that is larger than the RHS, use +.
1420 return SCEVAddExpr::get(LHS,
1421 getSCEV(I->getOperand(1)));
1422 }
1423 }
1424 break;
1425
Chris Lattner53e677a2004-04-02 20:23:17 +00001426 case Instruction::Shl:
1427 // Turn shift left of a constant amount into a multiply.
1428 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1429 Constant *X = ConstantInt::get(V->getType(), 1);
1430 X = ConstantExpr::getShl(X, SA);
1431 return SCEVMulExpr::get(getSCEV(I->getOperand(0)), getSCEV(X));
1432 }
1433 break;
1434
Reid Spencer3da59db2006-11-27 01:05:10 +00001435 case Instruction::Trunc:
Chris Lattner82e8a8f2006-12-11 00:12:31 +00001436 // We don't handle trunc to bool yet.
1437 if (I->getType()->isInteger())
Reid Spencer3da59db2006-11-27 01:05:10 +00001438 return SCEVTruncateExpr::get(getSCEV(I->getOperand(0)),
1439 I->getType()->getUnsignedVersion());
1440 break;
1441
1442 case Instruction::ZExt:
Chris Lattner82e8a8f2006-12-11 00:12:31 +00001443 // We don't handle zext from bool yet.
1444 if (I->getOperand(0)->getType()->isInteger())
Reid Spencer3da59db2006-11-27 01:05:10 +00001445 return SCEVZeroExtendExpr::get(getSCEV(I->getOperand(0)),
1446 I->getType()->getUnsignedVersion());
1447 break;
1448
1449 case Instruction::BitCast:
1450 // BitCasts are no-op casts so we just eliminate the cast.
Chris Lattner82e8a8f2006-12-11 00:12:31 +00001451 if (I->getType()->isInteger() && I->getOperand(0)->getType()->isInteger())
1452 return getSCEV(I->getOperand(0));
1453 break;
Chris Lattner53e677a2004-04-02 20:23:17 +00001454
1455 case Instruction::PHI:
1456 return createNodeForPHI(cast<PHINode>(I));
1457
1458 default: // We cannot analyze this expression.
1459 break;
1460 }
1461 }
1462
1463 return SCEVUnknown::get(V);
1464}
1465
1466
1467
1468//===----------------------------------------------------------------------===//
1469// Iteration Count Computation Code
1470//
1471
1472/// getIterationCount - If the specified loop has a predictable iteration
1473/// count, return it. Note that it is not valid to call this method on a
1474/// loop without a loop-invariant iteration count.
1475SCEVHandle ScalarEvolutionsImpl::getIterationCount(const Loop *L) {
1476 std::map<const Loop*, SCEVHandle>::iterator I = IterationCounts.find(L);
1477 if (I == IterationCounts.end()) {
1478 SCEVHandle ItCount = ComputeIterationCount(L);
1479 I = IterationCounts.insert(std::make_pair(L, ItCount)).first;
1480 if (ItCount != UnknownValue) {
1481 assert(ItCount->isLoopInvariant(L) &&
1482 "Computed trip count isn't loop invariant for loop!");
1483 ++NumTripCountsComputed;
1484 } else if (isa<PHINode>(L->getHeader()->begin())) {
1485 // Only count loops that have phi nodes as not being computable.
1486 ++NumTripCountsNotComputed;
1487 }
1488 }
1489 return I->second;
1490}
1491
1492/// ComputeIterationCount - Compute the number of times the specified loop
1493/// will iterate.
1494SCEVHandle ScalarEvolutionsImpl::ComputeIterationCount(const Loop *L) {
1495 // If the loop has a non-one exit block count, we can't analyze it.
Chris Lattnerf1ab4b42004-04-18 22:14:10 +00001496 std::vector<BasicBlock*> ExitBlocks;
1497 L->getExitBlocks(ExitBlocks);
1498 if (ExitBlocks.size() != 1) return UnknownValue;
Chris Lattner53e677a2004-04-02 20:23:17 +00001499
1500 // Okay, there is one exit block. Try to find the condition that causes the
1501 // loop to be exited.
Chris Lattnerf1ab4b42004-04-18 22:14:10 +00001502 BasicBlock *ExitBlock = ExitBlocks[0];
Chris Lattner53e677a2004-04-02 20:23:17 +00001503
1504 BasicBlock *ExitingBlock = 0;
1505 for (pred_iterator PI = pred_begin(ExitBlock), E = pred_end(ExitBlock);
1506 PI != E; ++PI)
1507 if (L->contains(*PI)) {
1508 if (ExitingBlock == 0)
1509 ExitingBlock = *PI;
1510 else
1511 return UnknownValue; // More than one block exiting!
1512 }
1513 assert(ExitingBlock && "No exits from loop, something is broken!");
1514
1515 // Okay, we've computed the exiting block. See what condition causes us to
1516 // exit.
1517 //
1518 // FIXME: we should be able to handle switch instructions (with a single exit)
1519 // FIXME: We should handle cast of int to bool as well
1520 BranchInst *ExitBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
1521 if (ExitBr == 0) return UnknownValue;
1522 assert(ExitBr->isConditional() && "If unconditional, it can't be in loop!");
1523 SetCondInst *ExitCond = dyn_cast<SetCondInst>(ExitBr->getCondition());
Chris Lattner7980fb92004-04-17 18:36:24 +00001524 if (ExitCond == 0) // Not a setcc
1525 return ComputeIterationCountExhaustively(L, ExitBr->getCondition(),
1526 ExitBr->getSuccessor(0) == ExitBlock);
Chris Lattner53e677a2004-04-02 20:23:17 +00001527
Chris Lattner673e02b2004-10-12 01:49:27 +00001528 // If the condition was exit on true, convert the condition to exit on false.
1529 Instruction::BinaryOps Cond;
1530 if (ExitBr->getSuccessor(1) == ExitBlock)
1531 Cond = ExitCond->getOpcode();
1532 else
1533 Cond = ExitCond->getInverseCondition();
1534
1535 // Handle common loops like: for (X = "string"; *X; ++X)
1536 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
1537 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
1538 SCEVHandle ItCnt =
1539 ComputeLoadConstantCompareIterationCount(LI, RHS, L, Cond);
1540 if (!isa<SCEVCouldNotCompute>(ItCnt)) return ItCnt;
1541 }
1542
Chris Lattner53e677a2004-04-02 20:23:17 +00001543 SCEVHandle LHS = getSCEV(ExitCond->getOperand(0));
1544 SCEVHandle RHS = getSCEV(ExitCond->getOperand(1));
1545
1546 // Try to evaluate any dependencies out of the loop.
1547 SCEVHandle Tmp = getSCEVAtScope(LHS, L);
1548 if (!isa<SCEVCouldNotCompute>(Tmp)) LHS = Tmp;
1549 Tmp = getSCEVAtScope(RHS, L);
1550 if (!isa<SCEVCouldNotCompute>(Tmp)) RHS = Tmp;
1551
Chris Lattner53e677a2004-04-02 20:23:17 +00001552 // At this point, we would like to compute how many iterations of the loop the
1553 // predicate will return true for these inputs.
1554 if (isa<SCEVConstant>(LHS) && !isa<SCEVConstant>(RHS)) {
1555 // If there is a constant, force it into the RHS.
1556 std::swap(LHS, RHS);
1557 Cond = SetCondInst::getSwappedCondition(Cond);
1558 }
1559
1560 // FIXME: think about handling pointer comparisons! i.e.:
1561 // while (P != P+100) ++P;
1562
1563 // If we have a comparison of a chrec against a constant, try to use value
1564 // ranges to answer this query.
1565 if (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
1566 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
1567 if (AddRec->getLoop() == L) {
1568 // Form the comparison range using the constant of the correct type so
1569 // that the ConstantRange class knows to do a signed or unsigned
1570 // comparison.
1571 ConstantInt *CompVal = RHSC->getValue();
1572 const Type *RealTy = ExitCond->getOperand(0)->getType();
Reid Spencer4da49122006-12-12 05:05:00 +00001573 CompVal = dyn_cast<ConstantInt>(
Reid Spencerb6ba3e62006-12-12 09:17:50 +00001574 ConstantExpr::getBitCast(CompVal, RealTy));
Chris Lattner53e677a2004-04-02 20:23:17 +00001575 if (CompVal) {
1576 // Form the constant range.
1577 ConstantRange CompRange(Cond, CompVal);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001578
Chris Lattner53e677a2004-04-02 20:23:17 +00001579 // Now that we have it, if it's signed, convert it to an unsigned
1580 // range.
1581 if (CompRange.getLower()->getType()->isSigned()) {
1582 const Type *NewTy = RHSC->getValue()->getType();
Reid Spencerb6ba3e62006-12-12 09:17:50 +00001583 Constant *NewL = ConstantExpr::getBitCast(CompRange.getLower(),
1584 NewTy);
1585 Constant *NewU = ConstantExpr::getBitCast(CompRange.getUpper(),
1586 NewTy);
Chris Lattner53e677a2004-04-02 20:23:17 +00001587 CompRange = ConstantRange(NewL, NewU);
1588 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001589
Chris Lattner53e677a2004-04-02 20:23:17 +00001590 SCEVHandle Ret = AddRec->getNumIterationsInRange(CompRange);
1591 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
1592 }
1593 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001594
Chris Lattner53e677a2004-04-02 20:23:17 +00001595 switch (Cond) {
1596 case Instruction::SetNE: // while (X != Y)
1597 // Convert to: while (X-Y != 0)
Chris Lattner7980fb92004-04-17 18:36:24 +00001598 if (LHS->getType()->isInteger()) {
Chris Lattnerbac5b462005-03-09 05:34:41 +00001599 SCEVHandle TC = HowFarToZero(SCEV::getMinusSCEV(LHS, RHS), L);
Chris Lattner7980fb92004-04-17 18:36:24 +00001600 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
1601 }
Chris Lattner53e677a2004-04-02 20:23:17 +00001602 break;
1603 case Instruction::SetEQ:
1604 // Convert to: while (X-Y == 0) // while (X == Y)
Chris Lattner7980fb92004-04-17 18:36:24 +00001605 if (LHS->getType()->isInteger()) {
Chris Lattnerbac5b462005-03-09 05:34:41 +00001606 SCEVHandle TC = HowFarToNonZero(SCEV::getMinusSCEV(LHS, RHS), L);
Chris Lattner7980fb92004-04-17 18:36:24 +00001607 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
1608 }
Chris Lattner53e677a2004-04-02 20:23:17 +00001609 break;
Chris Lattnerdb25de42005-08-15 23:33:51 +00001610 case Instruction::SetLT:
1611 if (LHS->getType()->isInteger() &&
1612 ExitCond->getOperand(0)->getType()->isSigned()) {
1613 SCEVHandle TC = HowManyLessThans(LHS, RHS, L);
1614 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
1615 }
1616 break;
1617 case Instruction::SetGT:
1618 if (LHS->getType()->isInteger() &&
1619 ExitCond->getOperand(0)->getType()->isSigned()) {
1620 SCEVHandle TC = HowManyLessThans(RHS, LHS, L);
1621 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
1622 }
1623 break;
Chris Lattner53e677a2004-04-02 20:23:17 +00001624 default:
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00001625#if 0
Bill Wendlinge8156192006-12-07 01:30:32 +00001626 cerr << "ComputeIterationCount ";
Chris Lattner53e677a2004-04-02 20:23:17 +00001627 if (ExitCond->getOperand(0)->getType()->isUnsigned())
Bill Wendlinge8156192006-12-07 01:30:32 +00001628 cerr << "[unsigned] ";
1629 cerr << *LHS << " "
1630 << Instruction::getOpcodeName(Cond) << " " << *RHS << "\n";
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00001631#endif
Chris Lattnere34c0b42004-04-03 00:43:03 +00001632 break;
Chris Lattner53e677a2004-04-02 20:23:17 +00001633 }
Chris Lattner7980fb92004-04-17 18:36:24 +00001634
1635 return ComputeIterationCountExhaustively(L, ExitCond,
1636 ExitBr->getSuccessor(0) == ExitBlock);
1637}
1638
Chris Lattner673e02b2004-10-12 01:49:27 +00001639static ConstantInt *
1640EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, Constant *C) {
1641 SCEVHandle InVal = SCEVConstant::get(cast<ConstantInt>(C));
1642 SCEVHandle Val = AddRec->evaluateAtIteration(InVal);
1643 assert(isa<SCEVConstant>(Val) &&
1644 "Evaluation of SCEV at constant didn't fold correctly?");
1645 return cast<SCEVConstant>(Val)->getValue();
1646}
1647
1648/// GetAddressedElementFromGlobal - Given a global variable with an initializer
1649/// and a GEP expression (missing the pointer index) indexing into it, return
1650/// the addressed element of the initializer or null if the index expression is
1651/// invalid.
1652static Constant *
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001653GetAddressedElementFromGlobal(GlobalVariable *GV,
Chris Lattner673e02b2004-10-12 01:49:27 +00001654 const std::vector<ConstantInt*> &Indices) {
1655 Constant *Init = GV->getInitializer();
1656 for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
Reid Spencerb83eb642006-10-20 07:07:24 +00001657 uint64_t Idx = Indices[i]->getZExtValue();
Chris Lattner673e02b2004-10-12 01:49:27 +00001658 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
1659 assert(Idx < CS->getNumOperands() && "Bad struct index!");
1660 Init = cast<Constant>(CS->getOperand(Idx));
1661 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
1662 if (Idx >= CA->getNumOperands()) return 0; // Bogus program
1663 Init = cast<Constant>(CA->getOperand(Idx));
1664 } else if (isa<ConstantAggregateZero>(Init)) {
1665 if (const StructType *STy = dyn_cast<StructType>(Init->getType())) {
1666 assert(Idx < STy->getNumElements() && "Bad struct index!");
1667 Init = Constant::getNullValue(STy->getElementType(Idx));
1668 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Init->getType())) {
1669 if (Idx >= ATy->getNumElements()) return 0; // Bogus program
1670 Init = Constant::getNullValue(ATy->getElementType());
1671 } else {
1672 assert(0 && "Unknown constant aggregate type!");
1673 }
1674 return 0;
1675 } else {
1676 return 0; // Unknown initializer type
1677 }
1678 }
1679 return Init;
1680}
1681
1682/// ComputeLoadConstantCompareIterationCount - Given an exit condition of
1683/// 'setcc load X, cst', try to se if we can compute the trip count.
1684SCEVHandle ScalarEvolutionsImpl::
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001685ComputeLoadConstantCompareIterationCount(LoadInst *LI, Constant *RHS,
Chris Lattner673e02b2004-10-12 01:49:27 +00001686 const Loop *L, unsigned SetCCOpcode) {
1687 if (LI->isVolatile()) return UnknownValue;
1688
1689 // Check to see if the loaded pointer is a getelementptr of a global.
1690 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
1691 if (!GEP) return UnknownValue;
1692
1693 // Make sure that it is really a constant global we are gepping, with an
1694 // initializer, and make sure the first IDX is really 0.
1695 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
1696 if (!GV || !GV->isConstant() || !GV->hasInitializer() ||
1697 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
1698 !cast<Constant>(GEP->getOperand(1))->isNullValue())
1699 return UnknownValue;
1700
1701 // Okay, we allow one non-constant index into the GEP instruction.
1702 Value *VarIdx = 0;
1703 std::vector<ConstantInt*> Indexes;
1704 unsigned VarIdxNum = 0;
1705 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
1706 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
1707 Indexes.push_back(CI);
1708 } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
1709 if (VarIdx) return UnknownValue; // Multiple non-constant idx's.
1710 VarIdx = GEP->getOperand(i);
1711 VarIdxNum = i-2;
1712 Indexes.push_back(0);
1713 }
1714
1715 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
1716 // Check to see if X is a loop variant variable value now.
1717 SCEVHandle Idx = getSCEV(VarIdx);
1718 SCEVHandle Tmp = getSCEVAtScope(Idx, L);
1719 if (!isa<SCEVCouldNotCompute>(Tmp)) Idx = Tmp;
1720
1721 // We can only recognize very limited forms of loop index expressions, in
1722 // particular, only affine AddRec's like {C1,+,C2}.
1723 SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
1724 if (!IdxExpr || !IdxExpr->isAffine() || IdxExpr->isLoopInvariant(L) ||
1725 !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
1726 !isa<SCEVConstant>(IdxExpr->getOperand(1)))
1727 return UnknownValue;
1728
1729 unsigned MaxSteps = MaxBruteForceIterations;
1730 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
Reid Spencerb83eb642006-10-20 07:07:24 +00001731 ConstantInt *ItCst =
1732 ConstantInt::get(IdxExpr->getType()->getUnsignedVersion(), IterationNum);
Chris Lattner673e02b2004-10-12 01:49:27 +00001733 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst);
1734
1735 // Form the GEP offset.
1736 Indexes[VarIdxNum] = Val;
1737
1738 Constant *Result = GetAddressedElementFromGlobal(GV, Indexes);
1739 if (Result == 0) break; // Cannot compute!
1740
1741 // Evaluate the condition for this iteration.
1742 Result = ConstantExpr::get(SetCCOpcode, Result, RHS);
1743 if (!isa<ConstantBool>(Result)) break; // Couldn't decide for sure
Chris Lattner003cbf32006-09-28 23:36:21 +00001744 if (cast<ConstantBool>(Result)->getValue() == false) {
Chris Lattner673e02b2004-10-12 01:49:27 +00001745#if 0
Bill Wendlinge8156192006-12-07 01:30:32 +00001746 cerr << "\n***\n*** Computed loop count " << *ItCst
1747 << "\n*** From global " << *GV << "*** BB: " << *L->getHeader()
1748 << "***\n";
Chris Lattner673e02b2004-10-12 01:49:27 +00001749#endif
1750 ++NumArrayLenItCounts;
1751 return SCEVConstant::get(ItCst); // Found terminating iteration!
1752 }
1753 }
1754 return UnknownValue;
1755}
1756
1757
Chris Lattner3221ad02004-04-17 22:58:41 +00001758/// CanConstantFold - Return true if we can constant fold an instruction of the
1759/// specified type, assuming that all operands were constants.
1760static bool CanConstantFold(const Instruction *I) {
1761 if (isa<BinaryOperator>(I) || isa<ShiftInst>(I) ||
1762 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I))
1763 return true;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001764
Chris Lattner3221ad02004-04-17 22:58:41 +00001765 if (const CallInst *CI = dyn_cast<CallInst>(I))
1766 if (const Function *F = CI->getCalledFunction())
1767 return canConstantFoldCallTo((Function*)F); // FIXME: elim cast
1768 return false;
Chris Lattner7980fb92004-04-17 18:36:24 +00001769}
1770
Chris Lattner3221ad02004-04-17 22:58:41 +00001771/// ConstantFold - Constant fold an instruction of the specified type with the
1772/// specified constant operands. This function may modify the operands vector.
1773static Constant *ConstantFold(const Instruction *I,
1774 std::vector<Constant*> &Operands) {
Chris Lattner7980fb92004-04-17 18:36:24 +00001775 if (isa<BinaryOperator>(I) || isa<ShiftInst>(I))
1776 return ConstantExpr::get(I->getOpcode(), Operands[0], Operands[1]);
1777
Reid Spencer3da59db2006-11-27 01:05:10 +00001778 if (isa<CastInst>(I))
1779 return ConstantExpr::getCast(I->getOpcode(), Operands[0], I->getType());
1780
Chris Lattner7980fb92004-04-17 18:36:24 +00001781 switch (I->getOpcode()) {
Chris Lattner7980fb92004-04-17 18:36:24 +00001782 case Instruction::Select:
1783 return ConstantExpr::getSelect(Operands[0], Operands[1], Operands[2]);
1784 case Instruction::Call:
Reid Spencere8404342004-07-18 00:18:30 +00001785 if (Function *GV = dyn_cast<Function>(Operands[0])) {
Chris Lattner7980fb92004-04-17 18:36:24 +00001786 Operands.erase(Operands.begin());
Reid Spencere8404342004-07-18 00:18:30 +00001787 return ConstantFoldCall(cast<Function>(GV), Operands);
Chris Lattner7980fb92004-04-17 18:36:24 +00001788 }
Chris Lattner7980fb92004-04-17 18:36:24 +00001789 return 0;
1790 case Instruction::GetElementPtr:
1791 Constant *Base = Operands[0];
1792 Operands.erase(Operands.begin());
1793 return ConstantExpr::getGetElementPtr(Base, Operands);
1794 }
1795 return 0;
1796}
1797
1798
Chris Lattner3221ad02004-04-17 22:58:41 +00001799/// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
1800/// in the loop that V is derived from. We allow arbitrary operations along the
1801/// way, but the operands of an operation must either be constants or a value
1802/// derived from a constant PHI. If this expression does not fit with these
1803/// constraints, return null.
1804static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
1805 // If this is not an instruction, or if this is an instruction outside of the
1806 // loop, it can't be derived from a loop PHI.
1807 Instruction *I = dyn_cast<Instruction>(V);
1808 if (I == 0 || !L->contains(I->getParent())) return 0;
1809
1810 if (PHINode *PN = dyn_cast<PHINode>(I))
1811 if (L->getHeader() == I->getParent())
1812 return PN;
1813 else
1814 // We don't currently keep track of the control flow needed to evaluate
1815 // PHIs, so we cannot handle PHIs inside of loops.
1816 return 0;
1817
1818 // If we won't be able to constant fold this expression even if the operands
1819 // are constants, return early.
1820 if (!CanConstantFold(I)) return 0;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001821
Chris Lattner3221ad02004-04-17 22:58:41 +00001822 // Otherwise, we can evaluate this instruction if all of its operands are
1823 // constant or derived from a PHI node themselves.
1824 PHINode *PHI = 0;
1825 for (unsigned Op = 0, e = I->getNumOperands(); Op != e; ++Op)
1826 if (!(isa<Constant>(I->getOperand(Op)) ||
1827 isa<GlobalValue>(I->getOperand(Op)))) {
1828 PHINode *P = getConstantEvolvingPHI(I->getOperand(Op), L);
1829 if (P == 0) return 0; // Not evolving from PHI
1830 if (PHI == 0)
1831 PHI = P;
1832 else if (PHI != P)
1833 return 0; // Evolving from multiple different PHIs.
1834 }
1835
1836 // This is a expression evolving from a constant PHI!
1837 return PHI;
1838}
1839
1840/// EvaluateExpression - Given an expression that passes the
1841/// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
1842/// in the loop has the value PHIVal. If we can't fold this expression for some
1843/// reason, return null.
1844static Constant *EvaluateExpression(Value *V, Constant *PHIVal) {
1845 if (isa<PHINode>(V)) return PHIVal;
Chris Lattner3221ad02004-04-17 22:58:41 +00001846 if (GlobalValue *GV = dyn_cast<GlobalValue>(V))
Reid Spencere8404342004-07-18 00:18:30 +00001847 return GV;
1848 if (Constant *C = dyn_cast<Constant>(V)) return C;
Chris Lattner3221ad02004-04-17 22:58:41 +00001849 Instruction *I = cast<Instruction>(V);
1850
1851 std::vector<Constant*> Operands;
1852 Operands.resize(I->getNumOperands());
1853
1854 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
1855 Operands[i] = EvaluateExpression(I->getOperand(i), PHIVal);
1856 if (Operands[i] == 0) return 0;
1857 }
1858
1859 return ConstantFold(I, Operands);
1860}
1861
1862/// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
1863/// in the header of its containing loop, we know the loop executes a
1864/// constant number of times, and the PHI node is just a recurrence
1865/// involving constants, fold it.
1866Constant *ScalarEvolutionsImpl::
1867getConstantEvolutionLoopExitValue(PHINode *PN, uint64_t Its, const Loop *L) {
1868 std::map<PHINode*, Constant*>::iterator I =
1869 ConstantEvolutionLoopExitValue.find(PN);
1870 if (I != ConstantEvolutionLoopExitValue.end())
1871 return I->second;
1872
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001873 if (Its > MaxBruteForceIterations)
Chris Lattner3221ad02004-04-17 22:58:41 +00001874 return ConstantEvolutionLoopExitValue[PN] = 0; // Not going to evaluate it.
1875
1876 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
1877
1878 // Since the loop is canonicalized, the PHI node must have two entries. One
1879 // entry must be a constant (coming in from outside of the loop), and the
1880 // second must be derived from the same PHI.
1881 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
1882 Constant *StartCST =
1883 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
1884 if (StartCST == 0)
1885 return RetVal = 0; // Must be a constant.
1886
1887 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
1888 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
1889 if (PN2 != PN)
1890 return RetVal = 0; // Not derived from same PHI.
1891
1892 // Execute the loop symbolically to determine the exit value.
1893 unsigned IterationNum = 0;
1894 unsigned NumIterations = Its;
1895 if (NumIterations != Its)
1896 return RetVal = 0; // More than 2^32 iterations??
1897
1898 for (Constant *PHIVal = StartCST; ; ++IterationNum) {
1899 if (IterationNum == NumIterations)
1900 return RetVal = PHIVal; // Got exit value!
1901
1902 // Compute the value of the PHI node for the next iteration.
1903 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
1904 if (NextPHI == PHIVal)
1905 return RetVal = NextPHI; // Stopped evolving!
1906 if (NextPHI == 0)
1907 return 0; // Couldn't evaluate!
1908 PHIVal = NextPHI;
1909 }
1910}
1911
Chris Lattner7980fb92004-04-17 18:36:24 +00001912/// ComputeIterationCountExhaustively - If the trip is known to execute a
1913/// constant number of times (the condition evolves only from constants),
1914/// try to evaluate a few iterations of the loop until we get the exit
1915/// condition gets a value of ExitWhen (true or false). If we cannot
1916/// evaluate the trip count of the loop, return UnknownValue.
1917SCEVHandle ScalarEvolutionsImpl::
1918ComputeIterationCountExhaustively(const Loop *L, Value *Cond, bool ExitWhen) {
1919 PHINode *PN = getConstantEvolvingPHI(Cond, L);
1920 if (PN == 0) return UnknownValue;
1921
1922 // Since the loop is canonicalized, the PHI node must have two entries. One
1923 // entry must be a constant (coming in from outside of the loop), and the
1924 // second must be derived from the same PHI.
1925 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
1926 Constant *StartCST =
1927 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
1928 if (StartCST == 0) return UnknownValue; // Must be a constant.
1929
1930 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
1931 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
1932 if (PN2 != PN) return UnknownValue; // Not derived from same PHI.
1933
1934 // Okay, we find a PHI node that defines the trip count of this loop. Execute
1935 // the loop symbolically to determine when the condition gets a value of
1936 // "ExitWhen".
1937 unsigned IterationNum = 0;
1938 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis.
1939 for (Constant *PHIVal = StartCST;
1940 IterationNum != MaxIterations; ++IterationNum) {
1941 ConstantBool *CondVal =
1942 dyn_cast_or_null<ConstantBool>(EvaluateExpression(Cond, PHIVal));
1943 if (!CondVal) return UnknownValue; // Couldn't symbolically evaluate.
Chris Lattner3221ad02004-04-17 22:58:41 +00001944
Chris Lattner7980fb92004-04-17 18:36:24 +00001945 if (CondVal->getValue() == ExitWhen) {
Chris Lattner3221ad02004-04-17 22:58:41 +00001946 ConstantEvolutionLoopExitValue[PN] = PHIVal;
Chris Lattner7980fb92004-04-17 18:36:24 +00001947 ++NumBruteForceTripCountsComputed;
Reid Spencerb83eb642006-10-20 07:07:24 +00001948 return SCEVConstant::get(ConstantInt::get(Type::UIntTy, IterationNum));
Chris Lattner7980fb92004-04-17 18:36:24 +00001949 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001950
Chris Lattner3221ad02004-04-17 22:58:41 +00001951 // Compute the value of the PHI node for the next iteration.
1952 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
1953 if (NextPHI == 0 || NextPHI == PHIVal)
Chris Lattner7980fb92004-04-17 18:36:24 +00001954 return UnknownValue; // Couldn't evaluate or not making progress...
Chris Lattner3221ad02004-04-17 22:58:41 +00001955 PHIVal = NextPHI;
Chris Lattner7980fb92004-04-17 18:36:24 +00001956 }
1957
1958 // Too many iterations were needed to evaluate.
Chris Lattner53e677a2004-04-02 20:23:17 +00001959 return UnknownValue;
1960}
1961
1962/// getSCEVAtScope - Compute the value of the specified expression within the
1963/// indicated loop (which may be null to indicate in no loop). If the
1964/// expression cannot be evaluated, return UnknownValue.
1965SCEVHandle ScalarEvolutionsImpl::getSCEVAtScope(SCEV *V, const Loop *L) {
1966 // FIXME: this should be turned into a virtual method on SCEV!
1967
Chris Lattner3221ad02004-04-17 22:58:41 +00001968 if (isa<SCEVConstant>(V)) return V;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001969
Chris Lattner3221ad02004-04-17 22:58:41 +00001970 // If this instruction is evolves from a constant-evolving PHI, compute the
1971 // exit value from the loop without using SCEVs.
1972 if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
1973 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
1974 const Loop *LI = this->LI[I->getParent()];
1975 if (LI && LI->getParentLoop() == L) // Looking for loop exit value.
1976 if (PHINode *PN = dyn_cast<PHINode>(I))
1977 if (PN->getParent() == LI->getHeader()) {
1978 // Okay, there is no closed form solution for the PHI node. Check
1979 // to see if the loop that contains it has a known iteration count.
1980 // If so, we may be able to force computation of the exit value.
1981 SCEVHandle IterationCount = getIterationCount(LI);
1982 if (SCEVConstant *ICC = dyn_cast<SCEVConstant>(IterationCount)) {
1983 // Okay, we know how many times the containing loop executes. If
1984 // this is a constant evolving PHI node, get the final value at
1985 // the specified iteration number.
1986 Constant *RV = getConstantEvolutionLoopExitValue(PN,
Reid Spencerb83eb642006-10-20 07:07:24 +00001987 ICC->getValue()->getZExtValue(),
Chris Lattner3221ad02004-04-17 22:58:41 +00001988 LI);
1989 if (RV) return SCEVUnknown::get(RV);
1990 }
1991 }
1992
Reid Spencer09906f32006-12-04 21:33:23 +00001993 // Okay, this is an expression that we cannot symbolically evaluate
Chris Lattner3221ad02004-04-17 22:58:41 +00001994 // into a SCEV. Check to see if it's possible to symbolically evaluate
Reid Spencer09906f32006-12-04 21:33:23 +00001995 // the arguments into constants, and if so, try to constant propagate the
Chris Lattner3221ad02004-04-17 22:58:41 +00001996 // result. This is particularly useful for computing loop exit values.
1997 if (CanConstantFold(I)) {
1998 std::vector<Constant*> Operands;
1999 Operands.reserve(I->getNumOperands());
2000 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
2001 Value *Op = I->getOperand(i);
2002 if (Constant *C = dyn_cast<Constant>(Op)) {
2003 Operands.push_back(C);
Chris Lattner3221ad02004-04-17 22:58:41 +00002004 } else {
2005 SCEVHandle OpV = getSCEVAtScope(getSCEV(Op), L);
2006 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(OpV))
Reid Spencerd977d862006-12-12 23:36:14 +00002007 Operands.push_back(ConstantExpr::getIntegerCast(SC->getValue(),
2008 Op->getType(),
2009 false));
Chris Lattner3221ad02004-04-17 22:58:41 +00002010 else if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(OpV)) {
2011 if (Constant *C = dyn_cast<Constant>(SU->getValue()))
Reid Spencerd977d862006-12-12 23:36:14 +00002012 Operands.push_back(ConstantExpr::getIntegerCast(C,
2013 Op->getType(),
2014 false));
Chris Lattner3221ad02004-04-17 22:58:41 +00002015 else
2016 return V;
2017 } else {
2018 return V;
2019 }
2020 }
2021 }
2022 return SCEVUnknown::get(ConstantFold(I, Operands));
2023 }
2024 }
2025
2026 // This is some other type of SCEVUnknown, just return it.
2027 return V;
2028 }
2029
Chris Lattner53e677a2004-04-02 20:23:17 +00002030 if (SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
2031 // Avoid performing the look-up in the common case where the specified
2032 // expression has no loop-variant portions.
2033 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
2034 SCEVHandle OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
2035 if (OpAtScope != Comm->getOperand(i)) {
2036 if (OpAtScope == UnknownValue) return UnknownValue;
2037 // Okay, at least one of these operands is loop variant but might be
2038 // foldable. Build a new instance of the folded commutative expression.
Chris Lattner3221ad02004-04-17 22:58:41 +00002039 std::vector<SCEVHandle> NewOps(Comm->op_begin(), Comm->op_begin()+i);
Chris Lattner53e677a2004-04-02 20:23:17 +00002040 NewOps.push_back(OpAtScope);
2041
2042 for (++i; i != e; ++i) {
2043 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
2044 if (OpAtScope == UnknownValue) return UnknownValue;
2045 NewOps.push_back(OpAtScope);
2046 }
2047 if (isa<SCEVAddExpr>(Comm))
2048 return SCEVAddExpr::get(NewOps);
2049 assert(isa<SCEVMulExpr>(Comm) && "Only know about add and mul!");
2050 return SCEVMulExpr::get(NewOps);
2051 }
2052 }
2053 // If we got here, all operands are loop invariant.
2054 return Comm;
2055 }
2056
Chris Lattner60a05cc2006-04-01 04:48:52 +00002057 if (SCEVSDivExpr *Div = dyn_cast<SCEVSDivExpr>(V)) {
2058 SCEVHandle LHS = getSCEVAtScope(Div->getLHS(), L);
Chris Lattner53e677a2004-04-02 20:23:17 +00002059 if (LHS == UnknownValue) return LHS;
Chris Lattner60a05cc2006-04-01 04:48:52 +00002060 SCEVHandle RHS = getSCEVAtScope(Div->getRHS(), L);
Chris Lattner53e677a2004-04-02 20:23:17 +00002061 if (RHS == UnknownValue) return RHS;
Chris Lattner60a05cc2006-04-01 04:48:52 +00002062 if (LHS == Div->getLHS() && RHS == Div->getRHS())
2063 return Div; // must be loop invariant
2064 return SCEVSDivExpr::get(LHS, RHS);
Chris Lattner53e677a2004-04-02 20:23:17 +00002065 }
2066
2067 // If this is a loop recurrence for a loop that does not contain L, then we
2068 // are dealing with the final value computed by the loop.
2069 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
2070 if (!L || !AddRec->getLoop()->contains(L->getHeader())) {
2071 // To evaluate this recurrence, we need to know how many times the AddRec
2072 // loop iterates. Compute this now.
2073 SCEVHandle IterationCount = getIterationCount(AddRec->getLoop());
2074 if (IterationCount == UnknownValue) return UnknownValue;
2075 IterationCount = getTruncateOrZeroExtend(IterationCount,
2076 AddRec->getType());
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002077
Chris Lattner53e677a2004-04-02 20:23:17 +00002078 // If the value is affine, simplify the expression evaluation to just
2079 // Start + Step*IterationCount.
2080 if (AddRec->isAffine())
2081 return SCEVAddExpr::get(AddRec->getStart(),
2082 SCEVMulExpr::get(IterationCount,
2083 AddRec->getOperand(1)));
2084
2085 // Otherwise, evaluate it the hard way.
2086 return AddRec->evaluateAtIteration(IterationCount);
2087 }
2088 return UnknownValue;
2089 }
2090
2091 //assert(0 && "Unknown SCEV type!");
2092 return UnknownValue;
2093}
2094
2095
2096/// SolveQuadraticEquation - Find the roots of the quadratic equation for the
2097/// given quadratic chrec {L,+,M,+,N}. This returns either the two roots (which
2098/// might be the same) or two SCEVCouldNotCompute objects.
2099///
2100static std::pair<SCEVHandle,SCEVHandle>
2101SolveQuadraticEquation(const SCEVAddRecExpr *AddRec) {
2102 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
2103 SCEVConstant *L = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
2104 SCEVConstant *M = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
2105 SCEVConstant *N = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002106
Chris Lattner53e677a2004-04-02 20:23:17 +00002107 // We currently can only solve this if the coefficients are constants.
2108 if (!L || !M || !N) {
2109 SCEV *CNC = new SCEVCouldNotCompute();
2110 return std::make_pair(CNC, CNC);
2111 }
2112
Reid Spencer1628cec2006-10-26 06:15:43 +00002113 Constant *C = L->getValue();
2114 Constant *Two = ConstantInt::get(C->getType(), 2);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002115
Chris Lattner53e677a2004-04-02 20:23:17 +00002116 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
Chris Lattner53e677a2004-04-02 20:23:17 +00002117 // The B coefficient is M-N/2
2118 Constant *B = ConstantExpr::getSub(M->getValue(),
Reid Spencer1628cec2006-10-26 06:15:43 +00002119 ConstantExpr::getSDiv(N->getValue(),
Chris Lattner53e677a2004-04-02 20:23:17 +00002120 Two));
2121 // The A coefficient is N/2
Reid Spencer1628cec2006-10-26 06:15:43 +00002122 Constant *A = ConstantExpr::getSDiv(N->getValue(), Two);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002123
Chris Lattner53e677a2004-04-02 20:23:17 +00002124 // Compute the B^2-4ac term.
2125 Constant *SqrtTerm =
2126 ConstantExpr::getMul(ConstantInt::get(C->getType(), 4),
2127 ConstantExpr::getMul(A, C));
2128 SqrtTerm = ConstantExpr::getSub(ConstantExpr::getMul(B, B), SqrtTerm);
2129
2130 // Compute floor(sqrt(B^2-4ac))
Reid Spencerb83eb642006-10-20 07:07:24 +00002131 ConstantInt *SqrtVal =
Reid Spencerd977d862006-12-12 23:36:14 +00002132 cast<ConstantInt>(ConstantExpr::getBitCast(SqrtTerm,
Chris Lattner53e677a2004-04-02 20:23:17 +00002133 SqrtTerm->getType()->getUnsignedVersion()));
Reid Spencerb83eb642006-10-20 07:07:24 +00002134 uint64_t SqrtValV = SqrtVal->getZExtValue();
Chris Lattner219c1412004-10-25 18:40:08 +00002135 uint64_t SqrtValV2 = (uint64_t)sqrt((double)SqrtValV);
Chris Lattner53e677a2004-04-02 20:23:17 +00002136 // The square root might not be precise for arbitrary 64-bit integer
2137 // values. Do some sanity checks to ensure it's correct.
2138 if (SqrtValV2*SqrtValV2 > SqrtValV ||
2139 (SqrtValV2+1)*(SqrtValV2+1) <= SqrtValV) {
2140 SCEV *CNC = new SCEVCouldNotCompute();
2141 return std::make_pair(CNC, CNC);
2142 }
2143
Reid Spencerb83eb642006-10-20 07:07:24 +00002144 SqrtVal = ConstantInt::get(Type::ULongTy, SqrtValV2);
Reid Spencerd977d862006-12-12 23:36:14 +00002145 SqrtTerm = ConstantExpr::getTruncOrBitCast(SqrtVal, SqrtTerm->getType());
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002146
Chris Lattner53e677a2004-04-02 20:23:17 +00002147 Constant *NegB = ConstantExpr::getNeg(B);
2148 Constant *TwoA = ConstantExpr::getMul(A, Two);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002149
Chris Lattner53e677a2004-04-02 20:23:17 +00002150 // The divisions must be performed as signed divisions.
2151 const Type *SignedTy = NegB->getType()->getSignedVersion();
Reid Spencerd977d862006-12-12 23:36:14 +00002152 NegB = ConstantExpr::getBitCast(NegB, SignedTy);
2153 TwoA = ConstantExpr::getBitCast(TwoA, SignedTy);
2154 SqrtTerm = ConstantExpr::getBitCast(SqrtTerm, SignedTy);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002155
Chris Lattner53e677a2004-04-02 20:23:17 +00002156 Constant *Solution1 =
Reid Spencer1628cec2006-10-26 06:15:43 +00002157 ConstantExpr::getSDiv(ConstantExpr::getAdd(NegB, SqrtTerm), TwoA);
Chris Lattner53e677a2004-04-02 20:23:17 +00002158 Constant *Solution2 =
Reid Spencer1628cec2006-10-26 06:15:43 +00002159 ConstantExpr::getSDiv(ConstantExpr::getSub(NegB, SqrtTerm), TwoA);
Chris Lattner53e677a2004-04-02 20:23:17 +00002160 return std::make_pair(SCEVUnknown::get(Solution1),
2161 SCEVUnknown::get(Solution2));
2162}
2163
2164/// HowFarToZero - Return the number of times a backedge comparing the specified
2165/// value to zero will execute. If not computable, return UnknownValue
2166SCEVHandle ScalarEvolutionsImpl::HowFarToZero(SCEV *V, const Loop *L) {
2167 // If the value is a constant
2168 if (SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
2169 // If the value is already zero, the branch will execute zero times.
2170 if (C->getValue()->isNullValue()) return C;
2171 return UnknownValue; // Otherwise it will loop infinitely.
2172 }
2173
2174 SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
2175 if (!AddRec || AddRec->getLoop() != L)
2176 return UnknownValue;
2177
2178 if (AddRec->isAffine()) {
2179 // If this is an affine expression the execution count of this branch is
2180 // equal to:
2181 //
2182 // (0 - Start/Step) iff Start % Step == 0
2183 //
2184 // Get the initial value for the loop.
2185 SCEVHandle Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
Chris Lattner4a2b23e2004-10-11 04:07:27 +00002186 if (isa<SCEVCouldNotCompute>(Start)) return UnknownValue;
Chris Lattner53e677a2004-04-02 20:23:17 +00002187 SCEVHandle Step = AddRec->getOperand(1);
2188
2189 Step = getSCEVAtScope(Step, L->getParentLoop());
2190
2191 // Figure out if Start % Step == 0.
2192 // FIXME: We should add DivExpr and RemExpr operations to our AST.
2193 if (SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step)) {
2194 if (StepC->getValue()->equalsInt(1)) // N % 1 == 0
Chris Lattnerbac5b462005-03-09 05:34:41 +00002195 return SCEV::getNegativeSCEV(Start); // 0 - Start/1 == -Start
Chris Lattner53e677a2004-04-02 20:23:17 +00002196 if (StepC->getValue()->isAllOnesValue()) // N % -1 == 0
2197 return Start; // 0 - Start/-1 == Start
2198
2199 // Check to see if Start is divisible by SC with no remainder.
2200 if (SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start)) {
2201 ConstantInt *StartCC = StartC->getValue();
2202 Constant *StartNegC = ConstantExpr::getNeg(StartCC);
Reid Spencer0a783f72006-11-02 01:53:59 +00002203 Constant *Rem = ConstantExpr::getSRem(StartNegC, StepC->getValue());
Chris Lattner53e677a2004-04-02 20:23:17 +00002204 if (Rem->isNullValue()) {
Reid Spencer1628cec2006-10-26 06:15:43 +00002205 Constant *Result =ConstantExpr::getSDiv(StartNegC,StepC->getValue());
Chris Lattner53e677a2004-04-02 20:23:17 +00002206 return SCEVUnknown::get(Result);
2207 }
2208 }
2209 }
2210 } else if (AddRec->isQuadratic() && AddRec->getType()->isInteger()) {
2211 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
2212 // the quadratic equation to solve it.
2213 std::pair<SCEVHandle,SCEVHandle> Roots = SolveQuadraticEquation(AddRec);
2214 SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
2215 SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
2216 if (R1) {
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00002217#if 0
Bill Wendlinge8156192006-12-07 01:30:32 +00002218 cerr << "HFTZ: " << *V << " - sol#1: " << *R1
2219 << " sol#2: " << *R2 << "\n";
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00002220#endif
Chris Lattner53e677a2004-04-02 20:23:17 +00002221 // Pick the smallest positive root value.
2222 assert(R1->getType()->isUnsigned()&&"Didn't canonicalize to unsigned?");
2223 if (ConstantBool *CB =
2224 dyn_cast<ConstantBool>(ConstantExpr::getSetLT(R1->getValue(),
2225 R2->getValue()))) {
Chris Lattner003cbf32006-09-28 23:36:21 +00002226 if (CB->getValue() == false)
Chris Lattner53e677a2004-04-02 20:23:17 +00002227 std::swap(R1, R2); // R1 is the minimum root now.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002228
Chris Lattner53e677a2004-04-02 20:23:17 +00002229 // We can only use this value if the chrec ends up with an exact zero
2230 // value at this index. When solving for "X*X != 5", for example, we
2231 // should not accept a root of 2.
2232 SCEVHandle Val = AddRec->evaluateAtIteration(R1);
2233 if (SCEVConstant *EvalVal = dyn_cast<SCEVConstant>(Val))
2234 if (EvalVal->getValue()->isNullValue())
2235 return R1; // We found a quadratic root!
2236 }
2237 }
2238 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002239
Chris Lattner53e677a2004-04-02 20:23:17 +00002240 return UnknownValue;
2241}
2242
2243/// HowFarToNonZero - Return the number of times a backedge checking the
2244/// specified value for nonzero will execute. If not computable, return
2245/// UnknownValue
2246SCEVHandle ScalarEvolutionsImpl::HowFarToNonZero(SCEV *V, const Loop *L) {
2247 // Loops that look like: while (X == 0) are very strange indeed. We don't
2248 // handle them yet except for the trivial case. This could be expanded in the
2249 // future as needed.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002250
Chris Lattner53e677a2004-04-02 20:23:17 +00002251 // If the value is a constant, check to see if it is known to be non-zero
2252 // already. If so, the backedge will execute zero times.
2253 if (SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
2254 Constant *Zero = Constant::getNullValue(C->getValue()->getType());
2255 Constant *NonZero = ConstantExpr::getSetNE(C->getValue(), Zero);
Chris Lattner003cbf32006-09-28 23:36:21 +00002256 if (NonZero == ConstantBool::getTrue())
Chris Lattner53e677a2004-04-02 20:23:17 +00002257 return getSCEV(Zero);
2258 return UnknownValue; // Otherwise it will loop infinitely.
2259 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002260
Chris Lattner53e677a2004-04-02 20:23:17 +00002261 // We could implement others, but I really doubt anyone writes loops like
2262 // this, and if they did, they would already be constant folded.
2263 return UnknownValue;
2264}
2265
Chris Lattnerdb25de42005-08-15 23:33:51 +00002266/// HowManyLessThans - Return the number of times a backedge containing the
2267/// specified less-than comparison will execute. If not computable, return
2268/// UnknownValue.
2269SCEVHandle ScalarEvolutionsImpl::
2270HowManyLessThans(SCEV *LHS, SCEV *RHS, const Loop *L) {
2271 // Only handle: "ADDREC < LoopInvariant".
2272 if (!RHS->isLoopInvariant(L)) return UnknownValue;
2273
2274 SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS);
2275 if (!AddRec || AddRec->getLoop() != L)
2276 return UnknownValue;
2277
2278 if (AddRec->isAffine()) {
2279 // FORNOW: We only support unit strides.
2280 SCEVHandle One = SCEVUnknown::getIntegerSCEV(1, RHS->getType());
2281 if (AddRec->getOperand(1) != One)
2282 return UnknownValue;
2283
2284 // The number of iterations for "[n,+,1] < m", is m-n. However, we don't
2285 // know that m is >= n on input to the loop. If it is, the condition return
2286 // true zero times. What we really should return, for full generality, is
2287 // SMAX(0, m-n). Since we cannot check this, we will instead check for a
2288 // canonical loop form: most do-loops will have a check that dominates the
2289 // loop, that only enters the loop if [n-1]<m. If we can find this check,
2290 // we know that the SMAX will evaluate to m-n, because we know that m >= n.
2291
2292 // Search for the check.
2293 BasicBlock *Preheader = L->getLoopPreheader();
2294 BasicBlock *PreheaderDest = L->getHeader();
2295 if (Preheader == 0) return UnknownValue;
2296
2297 BranchInst *LoopEntryPredicate =
2298 dyn_cast<BranchInst>(Preheader->getTerminator());
2299 if (!LoopEntryPredicate) return UnknownValue;
2300
2301 // This might be a critical edge broken out. If the loop preheader ends in
2302 // an unconditional branch to the loop, check to see if the preheader has a
2303 // single predecessor, and if so, look for its terminator.
2304 while (LoopEntryPredicate->isUnconditional()) {
2305 PreheaderDest = Preheader;
2306 Preheader = Preheader->getSinglePredecessor();
2307 if (!Preheader) return UnknownValue; // Multiple preds.
2308
2309 LoopEntryPredicate =
2310 dyn_cast<BranchInst>(Preheader->getTerminator());
2311 if (!LoopEntryPredicate) return UnknownValue;
2312 }
2313
2314 // Now that we found a conditional branch that dominates the loop, check to
2315 // see if it is the comparison we are looking for.
2316 SetCondInst *SCI =dyn_cast<SetCondInst>(LoopEntryPredicate->getCondition());
2317 if (!SCI) return UnknownValue;
2318 Value *PreCondLHS = SCI->getOperand(0);
2319 Value *PreCondRHS = SCI->getOperand(1);
2320 Instruction::BinaryOps Cond;
2321 if (LoopEntryPredicate->getSuccessor(0) == PreheaderDest)
2322 Cond = SCI->getOpcode();
2323 else
2324 Cond = SCI->getInverseCondition();
2325
2326 switch (Cond) {
2327 case Instruction::SetGT:
2328 std::swap(PreCondLHS, PreCondRHS);
2329 Cond = Instruction::SetLT;
2330 // Fall Through.
2331 case Instruction::SetLT:
2332 if (PreCondLHS->getType()->isInteger() &&
2333 PreCondLHS->getType()->isSigned()) {
2334 if (RHS != getSCEV(PreCondRHS))
2335 return UnknownValue; // Not a comparison against 'm'.
2336
2337 if (SCEV::getMinusSCEV(AddRec->getOperand(0), One)
2338 != getSCEV(PreCondLHS))
2339 return UnknownValue; // Not a comparison against 'n-1'.
2340 break;
2341 } else {
2342 return UnknownValue;
2343 }
2344 default: break;
2345 }
2346
Bill Wendlinge8156192006-12-07 01:30:32 +00002347 //cerr << "Computed Loop Trip Count as: "
2348 // << *SCEV::getMinusSCEV(RHS, AddRec->getOperand(0)) << "\n";
Chris Lattnerdb25de42005-08-15 23:33:51 +00002349 return SCEV::getMinusSCEV(RHS, AddRec->getOperand(0));
2350 }
2351
2352 return UnknownValue;
2353}
2354
Chris Lattner53e677a2004-04-02 20:23:17 +00002355/// getNumIterationsInRange - Return the number of iterations of this loop that
2356/// produce values in the specified constant range. Another way of looking at
2357/// this is that it returns the first iteration number where the value is not in
2358/// the condition, thus computing the exit count. If the iteration count can't
2359/// be computed, an instance of SCEVCouldNotCompute is returned.
2360SCEVHandle SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range) const {
2361 if (Range.isFullSet()) // Infinite loop.
2362 return new SCEVCouldNotCompute();
2363
2364 // If the start is a non-zero constant, shift the range to simplify things.
2365 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
2366 if (!SC->getValue()->isNullValue()) {
2367 std::vector<SCEVHandle> Operands(op_begin(), op_end());
Chris Lattnerb06432c2004-04-23 21:29:03 +00002368 Operands[0] = SCEVUnknown::getIntegerSCEV(0, SC->getType());
Chris Lattner53e677a2004-04-02 20:23:17 +00002369 SCEVHandle Shifted = SCEVAddRecExpr::get(Operands, getLoop());
2370 if (SCEVAddRecExpr *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted))
2371 return ShiftedAddRec->getNumIterationsInRange(
2372 Range.subtract(SC->getValue()));
2373 // This is strange and shouldn't happen.
2374 return new SCEVCouldNotCompute();
2375 }
2376
2377 // The only time we can solve this is when we have all constant indices.
2378 // Otherwise, we cannot determine the overflow conditions.
2379 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
2380 if (!isa<SCEVConstant>(getOperand(i)))
2381 return new SCEVCouldNotCompute();
2382
2383
2384 // Okay at this point we know that all elements of the chrec are constants and
2385 // that the start element is zero.
2386
2387 // First check to see if the range contains zero. If not, the first
2388 // iteration exits.
2389 ConstantInt *Zero = ConstantInt::get(getType(), 0);
2390 if (!Range.contains(Zero)) return SCEVConstant::get(Zero);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002391
Chris Lattner53e677a2004-04-02 20:23:17 +00002392 if (isAffine()) {
2393 // If this is an affine expression then we have this situation:
2394 // Solve {0,+,A} in Range === Ax in Range
2395
2396 // Since we know that zero is in the range, we know that the upper value of
2397 // the range must be the first possible exit value. Also note that we
2398 // already checked for a full range.
2399 ConstantInt *Upper = cast<ConstantInt>(Range.getUpper());
2400 ConstantInt *A = cast<SCEVConstant>(getOperand(1))->getValue();
2401 ConstantInt *One = ConstantInt::get(getType(), 1);
2402
2403 // The exit value should be (Upper+A-1)/A.
2404 Constant *ExitValue = Upper;
2405 if (A != One) {
2406 ExitValue = ConstantExpr::getSub(ConstantExpr::getAdd(Upper, A), One);
Reid Spencer1628cec2006-10-26 06:15:43 +00002407 ExitValue = ConstantExpr::getSDiv(ExitValue, A);
Chris Lattner53e677a2004-04-02 20:23:17 +00002408 }
2409 assert(isa<ConstantInt>(ExitValue) &&
2410 "Constant folding of integers not implemented?");
2411
2412 // Evaluate at the exit value. If we really did fall out of the valid
2413 // range, then we computed our trip count, otherwise wrap around or other
2414 // things must have happened.
2415 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue);
2416 if (Range.contains(Val))
2417 return new SCEVCouldNotCompute(); // Something strange happened
2418
2419 // Ensure that the previous value is in the range. This is a sanity check.
2420 assert(Range.contains(EvaluateConstantChrecAtConstant(this,
2421 ConstantExpr::getSub(ExitValue, One))) &&
2422 "Linear scev computation is off in a bad way!");
2423 return SCEVConstant::get(cast<ConstantInt>(ExitValue));
2424 } else if (isQuadratic()) {
2425 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
2426 // quadratic equation to solve it. To do this, we must frame our problem in
2427 // terms of figuring out when zero is crossed, instead of when
2428 // Range.getUpper() is crossed.
2429 std::vector<SCEVHandle> NewOps(op_begin(), op_end());
Chris Lattnerbac5b462005-03-09 05:34:41 +00002430 NewOps[0] = SCEV::getNegativeSCEV(SCEVUnknown::get(Range.getUpper()));
Chris Lattner53e677a2004-04-02 20:23:17 +00002431 SCEVHandle NewAddRec = SCEVAddRecExpr::get(NewOps, getLoop());
2432
2433 // Next, solve the constructed addrec
2434 std::pair<SCEVHandle,SCEVHandle> Roots =
2435 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec));
2436 SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
2437 SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
2438 if (R1) {
2439 // Pick the smallest positive root value.
2440 assert(R1->getType()->isUnsigned() && "Didn't canonicalize to unsigned?");
2441 if (ConstantBool *CB =
2442 dyn_cast<ConstantBool>(ConstantExpr::getSetLT(R1->getValue(),
2443 R2->getValue()))) {
Chris Lattner003cbf32006-09-28 23:36:21 +00002444 if (CB->getValue() == false)
Chris Lattner53e677a2004-04-02 20:23:17 +00002445 std::swap(R1, R2); // R1 is the minimum root now.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002446
Chris Lattner53e677a2004-04-02 20:23:17 +00002447 // Make sure the root is not off by one. The returned iteration should
2448 // not be in the range, but the previous one should be. When solving
2449 // for "X*X < 5", for example, we should not return a root of 2.
2450 ConstantInt *R1Val = EvaluateConstantChrecAtConstant(this,
2451 R1->getValue());
2452 if (Range.contains(R1Val)) {
2453 // The next iteration must be out of the range...
2454 Constant *NextVal =
2455 ConstantExpr::getAdd(R1->getValue(),
2456 ConstantInt::get(R1->getType(), 1));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002457
Chris Lattner53e677a2004-04-02 20:23:17 +00002458 R1Val = EvaluateConstantChrecAtConstant(this, NextVal);
2459 if (!Range.contains(R1Val))
2460 return SCEVUnknown::get(NextVal);
2461 return new SCEVCouldNotCompute(); // Something strange happened
2462 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002463
Chris Lattner53e677a2004-04-02 20:23:17 +00002464 // If R1 was not in the range, then it is a good return value. Make
2465 // sure that R1-1 WAS in the range though, just in case.
2466 Constant *NextVal =
2467 ConstantExpr::getSub(R1->getValue(),
2468 ConstantInt::get(R1->getType(), 1));
2469 R1Val = EvaluateConstantChrecAtConstant(this, NextVal);
2470 if (Range.contains(R1Val))
2471 return R1;
2472 return new SCEVCouldNotCompute(); // Something strange happened
2473 }
2474 }
2475 }
2476
2477 // Fallback, if this is a general polynomial, figure out the progression
2478 // through brute force: evaluate until we find an iteration that fails the
2479 // test. This is likely to be slow, but getting an accurate trip count is
2480 // incredibly important, we will be able to simplify the exit test a lot, and
2481 // we are almost guaranteed to get a trip count in this case.
2482 ConstantInt *TestVal = ConstantInt::get(getType(), 0);
2483 ConstantInt *One = ConstantInt::get(getType(), 1);
2484 ConstantInt *EndVal = TestVal; // Stop when we wrap around.
2485 do {
2486 ++NumBruteForceEvaluations;
2487 SCEVHandle Val = evaluateAtIteration(SCEVConstant::get(TestVal));
2488 if (!isa<SCEVConstant>(Val)) // This shouldn't happen.
2489 return new SCEVCouldNotCompute();
2490
2491 // Check to see if we found the value!
2492 if (!Range.contains(cast<SCEVConstant>(Val)->getValue()))
2493 return SCEVConstant::get(TestVal);
2494
2495 // Increment to test the next index.
2496 TestVal = cast<ConstantInt>(ConstantExpr::getAdd(TestVal, One));
2497 } while (TestVal != EndVal);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002498
Chris Lattner53e677a2004-04-02 20:23:17 +00002499 return new SCEVCouldNotCompute();
2500}
2501
2502
2503
2504//===----------------------------------------------------------------------===//
2505// ScalarEvolution Class Implementation
2506//===----------------------------------------------------------------------===//
2507
2508bool ScalarEvolution::runOnFunction(Function &F) {
2509 Impl = new ScalarEvolutionsImpl(F, getAnalysis<LoopInfo>());
2510 return false;
2511}
2512
2513void ScalarEvolution::releaseMemory() {
2514 delete (ScalarEvolutionsImpl*)Impl;
2515 Impl = 0;
2516}
2517
2518void ScalarEvolution::getAnalysisUsage(AnalysisUsage &AU) const {
2519 AU.setPreservesAll();
Chris Lattner53e677a2004-04-02 20:23:17 +00002520 AU.addRequiredTransitive<LoopInfo>();
2521}
2522
2523SCEVHandle ScalarEvolution::getSCEV(Value *V) const {
2524 return ((ScalarEvolutionsImpl*)Impl)->getSCEV(V);
2525}
2526
Chris Lattnera0740fb2005-08-09 23:36:33 +00002527/// hasSCEV - Return true if the SCEV for this value has already been
2528/// computed.
2529bool ScalarEvolution::hasSCEV(Value *V) const {
Chris Lattner05bd3742005-08-10 00:59:40 +00002530 return ((ScalarEvolutionsImpl*)Impl)->hasSCEV(V);
Chris Lattnera0740fb2005-08-09 23:36:33 +00002531}
2532
2533
2534/// setSCEV - Insert the specified SCEV into the map of current SCEVs for
2535/// the specified value.
2536void ScalarEvolution::setSCEV(Value *V, const SCEVHandle &H) {
2537 ((ScalarEvolutionsImpl*)Impl)->setSCEV(V, H);
2538}
2539
2540
Chris Lattner53e677a2004-04-02 20:23:17 +00002541SCEVHandle ScalarEvolution::getIterationCount(const Loop *L) const {
2542 return ((ScalarEvolutionsImpl*)Impl)->getIterationCount(L);
2543}
2544
2545bool ScalarEvolution::hasLoopInvariantIterationCount(const Loop *L) const {
2546 return !isa<SCEVCouldNotCompute>(getIterationCount(L));
2547}
2548
2549SCEVHandle ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) const {
2550 return ((ScalarEvolutionsImpl*)Impl)->getSCEVAtScope(getSCEV(V), L);
2551}
2552
2553void ScalarEvolution::deleteInstructionFromRecords(Instruction *I) const {
2554 return ((ScalarEvolutionsImpl*)Impl)->deleteInstructionFromRecords(I);
2555}
2556
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002557static void PrintLoopInfo(std::ostream &OS, const ScalarEvolution *SE,
Chris Lattner53e677a2004-04-02 20:23:17 +00002558 const Loop *L) {
2559 // Print all inner loops first
2560 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
2561 PrintLoopInfo(OS, SE, *I);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002562
Bill Wendlinge8156192006-12-07 01:30:32 +00002563 cerr << "Loop " << L->getHeader()->getName() << ": ";
Chris Lattnerf1ab4b42004-04-18 22:14:10 +00002564
2565 std::vector<BasicBlock*> ExitBlocks;
2566 L->getExitBlocks(ExitBlocks);
2567 if (ExitBlocks.size() != 1)
Bill Wendlinge8156192006-12-07 01:30:32 +00002568 cerr << "<multiple exits> ";
Chris Lattner53e677a2004-04-02 20:23:17 +00002569
2570 if (SE->hasLoopInvariantIterationCount(L)) {
Bill Wendlinge8156192006-12-07 01:30:32 +00002571 cerr << *SE->getIterationCount(L) << " iterations! ";
Chris Lattner53e677a2004-04-02 20:23:17 +00002572 } else {
Bill Wendlinge8156192006-12-07 01:30:32 +00002573 cerr << "Unpredictable iteration count. ";
Chris Lattner53e677a2004-04-02 20:23:17 +00002574 }
2575
Bill Wendlinge8156192006-12-07 01:30:32 +00002576 cerr << "\n";
Chris Lattner53e677a2004-04-02 20:23:17 +00002577}
2578
Reid Spencerce9653c2004-12-07 04:03:45 +00002579void ScalarEvolution::print(std::ostream &OS, const Module* ) const {
Chris Lattner53e677a2004-04-02 20:23:17 +00002580 Function &F = ((ScalarEvolutionsImpl*)Impl)->F;
2581 LoopInfo &LI = ((ScalarEvolutionsImpl*)Impl)->LI;
2582
2583 OS << "Classifying expressions for: " << F.getName() << "\n";
2584 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
Chris Lattner6ffe5512004-04-27 15:13:33 +00002585 if (I->getType()->isInteger()) {
2586 OS << *I;
Chris Lattner53e677a2004-04-02 20:23:17 +00002587 OS << " --> ";
Chris Lattner6ffe5512004-04-27 15:13:33 +00002588 SCEVHandle SV = getSCEV(&*I);
Chris Lattner53e677a2004-04-02 20:23:17 +00002589 SV->print(OS);
2590 OS << "\t\t";
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002591
Chris Lattner6ffe5512004-04-27 15:13:33 +00002592 if ((*I).getType()->isIntegral()) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002593 ConstantRange Bounds = SV->getValueRange();
2594 if (!Bounds.isFullSet())
2595 OS << "Bounds: " << Bounds << " ";
2596 }
2597
Chris Lattner6ffe5512004-04-27 15:13:33 +00002598 if (const Loop *L = LI.getLoopFor((*I).getParent())) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002599 OS << "Exits: ";
Chris Lattner6ffe5512004-04-27 15:13:33 +00002600 SCEVHandle ExitValue = getSCEVAtScope(&*I, L->getParentLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00002601 if (isa<SCEVCouldNotCompute>(ExitValue)) {
2602 OS << "<<Unknown>>";
2603 } else {
2604 OS << *ExitValue;
2605 }
2606 }
2607
2608
2609 OS << "\n";
2610 }
2611
2612 OS << "Determining loop execution counts for: " << F.getName() << "\n";
2613 for (LoopInfo::iterator I = LI.begin(), E = LI.end(); I != E; ++I)
2614 PrintLoopInfo(OS, this, *I);
2615}
2616