blob: 1df54c56ca459a7c8b1137615d5f30a5b934be48 [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 Lattner3b27d682006-12-19 22:30:33 +000062#define DEBUG_TYPE "scalar-evolution"
Chris Lattner0a7f98c2004-04-15 15:07:24 +000063#include "llvm/Analysis/ScalarEvolutionExpressions.h"
Chris Lattner53e677a2004-04-02 20:23:17 +000064#include "llvm/Constants.h"
65#include "llvm/DerivedTypes.h"
Chris Lattner673e02b2004-10-12 01:49:27 +000066#include "llvm/GlobalVariable.h"
Chris Lattner53e677a2004-04-02 20:23:17 +000067#include "llvm/Instructions.h"
John Criswella1156432005-10-27 15:54:34 +000068#include "llvm/Analysis/ConstantFolding.h"
Chris Lattner53e677a2004-04-02 20:23:17 +000069#include "llvm/Analysis/LoopInfo.h"
70#include "llvm/Assembly/Writer.h"
71#include "llvm/Transforms/Scalar.h"
72#include "llvm/Support/CFG.h"
Chris Lattner95255282006-06-28 23:17:24 +000073#include "llvm/Support/CommandLine.h"
Chris Lattnerb3364092006-10-04 21:49:37 +000074#include "llvm/Support/Compiler.h"
Chris Lattner53e677a2004-04-02 20:23:17 +000075#include "llvm/Support/ConstantRange.h"
76#include "llvm/Support/InstIterator.h"
Chris Lattnerb3364092006-10-04 21:49:37 +000077#include "llvm/Support/ManagedStatic.h"
Chris Lattner75de5ab2006-12-19 01:16:02 +000078#include "llvm/Support/MathExtras.h"
Bill Wendling6f81b512006-11-28 22:46:12 +000079#include "llvm/Support/Streams.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000080#include "llvm/ADT/Statistic.h"
Bill Wendling6f81b512006-11-28 22:46:12 +000081#include <ostream>
Alkis Evlogimenos20aa4742004-09-03 18:19:51 +000082#include <algorithm>
Jeff Cohen97af7512006-12-02 02:22:01 +000083#include <cmath>
Chris Lattner53e677a2004-04-02 20:23:17 +000084using namespace llvm;
85
Chris Lattner3b27d682006-12-19 22:30:33 +000086STATISTIC(NumBruteForceEvaluations,
87 "Number of brute force evaluations needed to "
88 "calculate high-order polynomial exit values");
89STATISTIC(NumArrayLenItCounts,
90 "Number of trip counts computed with array length");
91STATISTIC(NumTripCountsComputed,
92 "Number of loops with predictable loop counts");
93STATISTIC(NumTripCountsNotComputed,
94 "Number of loops without predictable loop counts");
95STATISTIC(NumBruteForceTripCountsComputed,
96 "Number of loops with trip counts computed by force");
97
98cl::opt<unsigned>
99MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden,
100 cl::desc("Maximum number of iterations SCEV will "
101 "symbolically execute a constant derived loop"),
102 cl::init(100));
103
Chris Lattner53e677a2004-04-02 20:23:17 +0000104namespace {
Chris Lattner5d8925c2006-08-27 22:30:17 +0000105 RegisterPass<ScalarEvolution>
Chris Lattner45a1cf82004-04-19 03:42:32 +0000106 R("scalar-evolution", "Scalar Evolution Analysis");
Chris Lattner53e677a2004-04-02 20:23:17 +0000107}
108
109//===----------------------------------------------------------------------===//
110// SCEV class definitions
111//===----------------------------------------------------------------------===//
112
113//===----------------------------------------------------------------------===//
114// Implementation of the SCEV class.
115//
Chris Lattner53e677a2004-04-02 20:23:17 +0000116SCEV::~SCEV() {}
117void SCEV::dump() const {
Bill Wendlinge8156192006-12-07 01:30:32 +0000118 print(cerr);
Chris Lattner53e677a2004-04-02 20:23:17 +0000119}
120
121/// getValueRange - Return the tightest constant bounds that this value is
122/// known to have. This method is only valid on integer SCEV objects.
123ConstantRange SCEV::getValueRange() const {
124 const Type *Ty = getType();
Chris Lattner42a75512007-01-15 02:27:26 +0000125 assert(Ty->isInteger() && "Can't get range for a non-integer SCEV!");
Chris Lattner53e677a2004-04-02 20:23:17 +0000126 // Default to a full range if no better information is available.
127 return ConstantRange(getType());
128}
129
130
131SCEVCouldNotCompute::SCEVCouldNotCompute() : SCEV(scCouldNotCompute) {}
132
133bool SCEVCouldNotCompute::isLoopInvariant(const Loop *L) const {
134 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
Misha Brukmanbb2aff12004-04-05 19:00:46 +0000135 return false;
Chris Lattner53e677a2004-04-02 20:23:17 +0000136}
137
138const Type *SCEVCouldNotCompute::getType() const {
139 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
Misha Brukmanbb2aff12004-04-05 19:00:46 +0000140 return 0;
Chris Lattner53e677a2004-04-02 20:23:17 +0000141}
142
143bool SCEVCouldNotCompute::hasComputableLoopEvolution(const Loop *L) const {
144 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
145 return false;
146}
147
Chris Lattner4dc534c2005-02-13 04:37:18 +0000148SCEVHandle SCEVCouldNotCompute::
149replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
150 const SCEVHandle &Conc) const {
151 return this;
152}
153
Chris Lattner53e677a2004-04-02 20:23:17 +0000154void SCEVCouldNotCompute::print(std::ostream &OS) const {
155 OS << "***COULDNOTCOMPUTE***";
156}
157
158bool SCEVCouldNotCompute::classof(const SCEV *S) {
159 return S->getSCEVType() == scCouldNotCompute;
160}
161
162
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000163// SCEVConstants - Only allow the creation of one SCEVConstant for any
164// particular value. Don't use a SCEVHandle here, or else the object will
165// never be deleted!
Chris Lattnerb3364092006-10-04 21:49:37 +0000166static ManagedStatic<std::map<ConstantInt*, SCEVConstant*> > SCEVConstants;
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000167
Chris Lattner53e677a2004-04-02 20:23:17 +0000168
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000169SCEVConstant::~SCEVConstant() {
Chris Lattnerb3364092006-10-04 21:49:37 +0000170 SCEVConstants->erase(V);
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000171}
Chris Lattner53e677a2004-04-02 20:23:17 +0000172
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000173SCEVHandle SCEVConstant::get(ConstantInt *V) {
Chris Lattnerb3364092006-10-04 21:49:37 +0000174 SCEVConstant *&R = (*SCEVConstants)[V];
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000175 if (R == 0) R = new SCEVConstant(V);
176 return R;
177}
Chris Lattner53e677a2004-04-02 20:23:17 +0000178
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000179ConstantRange SCEVConstant::getValueRange() const {
180 return ConstantRange(V);
181}
Chris Lattner53e677a2004-04-02 20:23:17 +0000182
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000183const Type *SCEVConstant::getType() const { return V->getType(); }
Chris Lattner53e677a2004-04-02 20:23:17 +0000184
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000185void SCEVConstant::print(std::ostream &OS) const {
186 WriteAsOperand(OS, V, false);
187}
Chris Lattner53e677a2004-04-02 20:23:17 +0000188
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000189// SCEVTruncates - Only allow the creation of one SCEVTruncateExpr for any
190// particular input. Don't use a SCEVHandle here, or else the object will
191// never be deleted!
Chris Lattnerb3364092006-10-04 21:49:37 +0000192static ManagedStatic<std::map<std::pair<SCEV*, const Type*>,
193 SCEVTruncateExpr*> > SCEVTruncates;
Chris Lattner53e677a2004-04-02 20:23:17 +0000194
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000195SCEVTruncateExpr::SCEVTruncateExpr(const SCEVHandle &op, const Type *ty)
196 : SCEV(scTruncate), Op(op), Ty(ty) {
Chris Lattner42a75512007-01-15 02:27:26 +0000197 assert(Op->getType()->isInteger() && Ty->isInteger() &&
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000198 "Cannot truncate non-integer value!");
Reid Spencere7ca0422007-01-08 01:26:33 +0000199 assert(Op->getType()->getPrimitiveSizeInBits() > Ty->getPrimitiveSizeInBits()
200 && "This is not a truncating conversion!");
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000201}
Chris Lattner53e677a2004-04-02 20:23:17 +0000202
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000203SCEVTruncateExpr::~SCEVTruncateExpr() {
Chris Lattnerb3364092006-10-04 21:49:37 +0000204 SCEVTruncates->erase(std::make_pair(Op, Ty));
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000205}
Chris Lattner53e677a2004-04-02 20:23:17 +0000206
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000207ConstantRange SCEVTruncateExpr::getValueRange() const {
208 return getOperand()->getValueRange().truncate(getType());
209}
Chris Lattner53e677a2004-04-02 20:23:17 +0000210
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000211void SCEVTruncateExpr::print(std::ostream &OS) const {
212 OS << "(truncate " << *Op << " to " << *Ty << ")";
213}
214
215// SCEVZeroExtends - Only allow the creation of one SCEVZeroExtendExpr for any
216// particular input. Don't use a SCEVHandle here, or else the object will never
217// be deleted!
Chris Lattnerb3364092006-10-04 21:49:37 +0000218static ManagedStatic<std::map<std::pair<SCEV*, const Type*>,
219 SCEVZeroExtendExpr*> > SCEVZeroExtends;
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000220
221SCEVZeroExtendExpr::SCEVZeroExtendExpr(const SCEVHandle &op, const Type *ty)
Reid Spencer48d8a702006-11-01 21:53:12 +0000222 : SCEV(scZeroExtend), Op(op), Ty(ty) {
Chris Lattner42a75512007-01-15 02:27:26 +0000223 assert(Op->getType()->isInteger() && Ty->isInteger() &&
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000224 "Cannot zero extend non-integer value!");
Reid Spencere7ca0422007-01-08 01:26:33 +0000225 assert(Op->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits()
226 && "This is not an extending conversion!");
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000227}
228
229SCEVZeroExtendExpr::~SCEVZeroExtendExpr() {
Chris Lattnerb3364092006-10-04 21:49:37 +0000230 SCEVZeroExtends->erase(std::make_pair(Op, Ty));
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000231}
232
233ConstantRange SCEVZeroExtendExpr::getValueRange() const {
234 return getOperand()->getValueRange().zeroExtend(getType());
235}
236
237void SCEVZeroExtendExpr::print(std::ostream &OS) const {
238 OS << "(zeroextend " << *Op << " to " << *Ty << ")";
239}
240
241// SCEVCommExprs - Only allow the creation of one SCEVCommutativeExpr for any
242// particular input. Don't use a SCEVHandle here, or else the object will never
243// be deleted!
Chris Lattnerb3364092006-10-04 21:49:37 +0000244static ManagedStatic<std::map<std::pair<unsigned, std::vector<SCEV*> >,
245 SCEVCommutativeExpr*> > SCEVCommExprs;
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000246
247SCEVCommutativeExpr::~SCEVCommutativeExpr() {
Chris Lattnerb3364092006-10-04 21:49:37 +0000248 SCEVCommExprs->erase(std::make_pair(getSCEVType(),
249 std::vector<SCEV*>(Operands.begin(),
250 Operands.end())));
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000251}
252
253void SCEVCommutativeExpr::print(std::ostream &OS) const {
254 assert(Operands.size() > 1 && "This plus expr shouldn't exist!");
255 const char *OpStr = getOperationStr();
256 OS << "(" << *Operands[0];
257 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
258 OS << OpStr << *Operands[i];
259 OS << ")";
260}
261
Chris Lattner4dc534c2005-02-13 04:37:18 +0000262SCEVHandle SCEVCommutativeExpr::
263replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
264 const SCEVHandle &Conc) const {
265 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
266 SCEVHandle H = getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc);
267 if (H != getOperand(i)) {
268 std::vector<SCEVHandle> NewOps;
269 NewOps.reserve(getNumOperands());
270 for (unsigned j = 0; j != i; ++j)
271 NewOps.push_back(getOperand(j));
272 NewOps.push_back(H);
273 for (++i; i != e; ++i)
274 NewOps.push_back(getOperand(i)->
275 replaceSymbolicValuesWithConcrete(Sym, Conc));
276
277 if (isa<SCEVAddExpr>(this))
278 return SCEVAddExpr::get(NewOps);
279 else if (isa<SCEVMulExpr>(this))
280 return SCEVMulExpr::get(NewOps);
281 else
282 assert(0 && "Unknown commutative expr!");
283 }
284 }
285 return this;
286}
287
288
Chris Lattner60a05cc2006-04-01 04:48:52 +0000289// SCEVSDivs - Only allow the creation of one SCEVSDivExpr for any particular
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000290// input. Don't use a SCEVHandle here, or else the object will never be
291// deleted!
Chris Lattnerb3364092006-10-04 21:49:37 +0000292static ManagedStatic<std::map<std::pair<SCEV*, SCEV*>,
293 SCEVSDivExpr*> > SCEVSDivs;
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000294
Chris Lattner60a05cc2006-04-01 04:48:52 +0000295SCEVSDivExpr::~SCEVSDivExpr() {
Chris Lattnerb3364092006-10-04 21:49:37 +0000296 SCEVSDivs->erase(std::make_pair(LHS, RHS));
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000297}
298
Chris Lattner60a05cc2006-04-01 04:48:52 +0000299void SCEVSDivExpr::print(std::ostream &OS) const {
300 OS << "(" << *LHS << " /s " << *RHS << ")";
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000301}
302
Chris Lattner60a05cc2006-04-01 04:48:52 +0000303const Type *SCEVSDivExpr::getType() const {
Reid Spencerc5b206b2006-12-31 05:48:39 +0000304 return LHS->getType();
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000305}
306
307// SCEVAddRecExprs - Only allow the creation of one SCEVAddRecExpr for any
308// particular input. Don't use a SCEVHandle here, or else the object will never
309// be deleted!
Chris Lattnerb3364092006-10-04 21:49:37 +0000310static ManagedStatic<std::map<std::pair<const Loop *, std::vector<SCEV*> >,
311 SCEVAddRecExpr*> > SCEVAddRecExprs;
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000312
313SCEVAddRecExpr::~SCEVAddRecExpr() {
Chris Lattnerb3364092006-10-04 21:49:37 +0000314 SCEVAddRecExprs->erase(std::make_pair(L,
315 std::vector<SCEV*>(Operands.begin(),
316 Operands.end())));
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000317}
318
Chris Lattner4dc534c2005-02-13 04:37:18 +0000319SCEVHandle SCEVAddRecExpr::
320replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
321 const SCEVHandle &Conc) const {
322 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
323 SCEVHandle H = getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc);
324 if (H != getOperand(i)) {
325 std::vector<SCEVHandle> NewOps;
326 NewOps.reserve(getNumOperands());
327 for (unsigned j = 0; j != i; ++j)
328 NewOps.push_back(getOperand(j));
329 NewOps.push_back(H);
330 for (++i; i != e; ++i)
331 NewOps.push_back(getOperand(i)->
332 replaceSymbolicValuesWithConcrete(Sym, Conc));
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000333
Chris Lattner4dc534c2005-02-13 04:37:18 +0000334 return get(NewOps, L);
335 }
336 }
337 return this;
338}
339
340
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000341bool SCEVAddRecExpr::isLoopInvariant(const Loop *QueryLoop) const {
342 // This recurrence is invariant w.r.t to QueryLoop iff QueryLoop doesn't
Chris Lattnerff2006a2005-08-16 00:37:01 +0000343 // contain L and if the start is invariant.
344 return !QueryLoop->contains(L->getHeader()) &&
345 getOperand(0)->isLoopInvariant(QueryLoop);
Chris Lattner53e677a2004-04-02 20:23:17 +0000346}
347
348
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000349void SCEVAddRecExpr::print(std::ostream &OS) const {
350 OS << "{" << *Operands[0];
351 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
352 OS << ",+," << *Operands[i];
353 OS << "}<" << L->getHeader()->getName() + ">";
354}
Chris Lattner53e677a2004-04-02 20:23:17 +0000355
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000356// SCEVUnknowns - Only allow the creation of one SCEVUnknown for any particular
357// value. Don't use a SCEVHandle here, or else the object will never be
358// deleted!
Chris Lattnerb3364092006-10-04 21:49:37 +0000359static ManagedStatic<std::map<Value*, SCEVUnknown*> > SCEVUnknowns;
Chris Lattner53e677a2004-04-02 20:23:17 +0000360
Chris Lattnerb3364092006-10-04 21:49:37 +0000361SCEVUnknown::~SCEVUnknown() { SCEVUnknowns->erase(V); }
Chris Lattner53e677a2004-04-02 20:23:17 +0000362
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000363bool SCEVUnknown::isLoopInvariant(const Loop *L) const {
364 // All non-instruction values are loop invariant. All instructions are loop
365 // invariant if they are not contained in the specified loop.
366 if (Instruction *I = dyn_cast<Instruction>(V))
367 return !L->contains(I->getParent());
368 return true;
369}
Chris Lattner53e677a2004-04-02 20:23:17 +0000370
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000371const Type *SCEVUnknown::getType() const {
372 return V->getType();
373}
Chris Lattner53e677a2004-04-02 20:23:17 +0000374
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000375void SCEVUnknown::print(std::ostream &OS) const {
376 WriteAsOperand(OS, V, false);
Chris Lattner53e677a2004-04-02 20:23:17 +0000377}
378
Chris Lattner8d741b82004-06-20 06:23:15 +0000379//===----------------------------------------------------------------------===//
380// SCEV Utilities
381//===----------------------------------------------------------------------===//
382
383namespace {
384 /// SCEVComplexityCompare - Return true if the complexity of the LHS is less
385 /// than the complexity of the RHS. This comparator is used to canonicalize
386 /// expressions.
Chris Lattner95255282006-06-28 23:17:24 +0000387 struct VISIBILITY_HIDDEN SCEVComplexityCompare {
Chris Lattner8d741b82004-06-20 06:23:15 +0000388 bool operator()(SCEV *LHS, SCEV *RHS) {
389 return LHS->getSCEVType() < RHS->getSCEVType();
390 }
391 };
392}
393
394/// GroupByComplexity - Given a list of SCEV objects, order them by their
395/// complexity, and group objects of the same complexity together by value.
396/// When this routine is finished, we know that any duplicates in the vector are
397/// consecutive and that complexity is monotonically increasing.
398///
399/// Note that we go take special precautions to ensure that we get determinstic
400/// results from this routine. In other words, we don't want the results of
401/// this to depend on where the addresses of various SCEV objects happened to
402/// land in memory.
403///
404static void GroupByComplexity(std::vector<SCEVHandle> &Ops) {
405 if (Ops.size() < 2) return; // Noop
406 if (Ops.size() == 2) {
407 // This is the common case, which also happens to be trivially simple.
408 // Special case it.
409 if (Ops[0]->getSCEVType() > Ops[1]->getSCEVType())
410 std::swap(Ops[0], Ops[1]);
411 return;
412 }
413
414 // Do the rough sort by complexity.
415 std::sort(Ops.begin(), Ops.end(), SCEVComplexityCompare());
416
417 // Now that we are sorted by complexity, group elements of the same
418 // complexity. Note that this is, at worst, N^2, but the vector is likely to
419 // be extremely short in practice. Note that we take this approach because we
420 // do not want to depend on the addresses of the objects we are grouping.
Chris Lattner2d584522004-06-20 17:01:44 +0000421 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
Chris Lattner8d741b82004-06-20 06:23:15 +0000422 SCEV *S = Ops[i];
423 unsigned Complexity = S->getSCEVType();
424
425 // If there are any objects of the same complexity and same value as this
426 // one, group them.
427 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
428 if (Ops[j] == S) { // Found a duplicate.
429 // Move it to immediately after i'th element.
430 std::swap(Ops[i+1], Ops[j]);
431 ++i; // no need to rescan it.
Chris Lattner541ad5e2004-06-20 20:32:16 +0000432 if (i == e-2) return; // Done!
Chris Lattner8d741b82004-06-20 06:23:15 +0000433 }
434 }
435 }
436}
437
Chris Lattner53e677a2004-04-02 20:23:17 +0000438
Chris Lattner53e677a2004-04-02 20:23:17 +0000439
440//===----------------------------------------------------------------------===//
441// Simple SCEV method implementations
442//===----------------------------------------------------------------------===//
443
444/// getIntegerSCEV - Given an integer or FP type, create a constant for the
445/// specified signed integer value and return a SCEV for the constant.
Chris Lattnerb06432c2004-04-23 21:29:03 +0000446SCEVHandle SCEVUnknown::getIntegerSCEV(int Val, const Type *Ty) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000447 Constant *C;
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000448 if (Val == 0)
Chris Lattner53e677a2004-04-02 20:23:17 +0000449 C = Constant::getNullValue(Ty);
450 else if (Ty->isFloatingPoint())
451 C = ConstantFP::get(Ty, Val);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000452 else
Reid Spencerb83eb642006-10-20 07:07:24 +0000453 C = ConstantInt::get(Ty, Val);
Chris Lattner53e677a2004-04-02 20:23:17 +0000454 return SCEVUnknown::get(C);
455}
456
457/// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion of the
458/// input value to the specified type. If the type must be extended, it is zero
459/// extended.
460static SCEVHandle getTruncateOrZeroExtend(const SCEVHandle &V, const Type *Ty) {
461 const Type *SrcTy = V->getType();
Chris Lattner42a75512007-01-15 02:27:26 +0000462 assert(SrcTy->isInteger() && Ty->isInteger() &&
Chris Lattner53e677a2004-04-02 20:23:17 +0000463 "Cannot truncate or zero extend with non-integer arguments!");
Reid Spencere7ca0422007-01-08 01:26:33 +0000464 if (SrcTy->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
Chris Lattner53e677a2004-04-02 20:23:17 +0000465 return V; // No conversion
Reid Spencere7ca0422007-01-08 01:26:33 +0000466 if (SrcTy->getPrimitiveSizeInBits() > Ty->getPrimitiveSizeInBits())
Chris Lattner53e677a2004-04-02 20:23:17 +0000467 return SCEVTruncateExpr::get(V, Ty);
468 return SCEVZeroExtendExpr::get(V, Ty);
469}
470
471/// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V
472///
Chris Lattnerbac5b462005-03-09 05:34:41 +0000473SCEVHandle SCEV::getNegativeSCEV(const SCEVHandle &V) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000474 if (SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
475 return SCEVUnknown::get(ConstantExpr::getNeg(VC->getValue()));
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000476
Chris Lattnerb06432c2004-04-23 21:29:03 +0000477 return SCEVMulExpr::get(V, SCEVUnknown::getIntegerSCEV(-1, V->getType()));
Chris Lattner53e677a2004-04-02 20:23:17 +0000478}
479
480/// getMinusSCEV - Return a SCEV corresponding to LHS - RHS.
481///
Chris Lattnerbac5b462005-03-09 05:34:41 +0000482SCEVHandle SCEV::getMinusSCEV(const SCEVHandle &LHS, const SCEVHandle &RHS) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000483 // X - Y --> X + -Y
Chris Lattnerbac5b462005-03-09 05:34:41 +0000484 return SCEVAddExpr::get(LHS, SCEV::getNegativeSCEV(RHS));
Chris Lattner53e677a2004-04-02 20:23:17 +0000485}
486
487
Chris Lattner53e677a2004-04-02 20:23:17 +0000488/// PartialFact - Compute V!/(V-NumSteps)!
489static SCEVHandle PartialFact(SCEVHandle V, unsigned NumSteps) {
490 // Handle this case efficiently, it is common to have constant iteration
491 // counts while computing loop exit values.
492 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(V)) {
Reid Spencerb83eb642006-10-20 07:07:24 +0000493 uint64_t Val = SC->getValue()->getZExtValue();
Chris Lattner53e677a2004-04-02 20:23:17 +0000494 uint64_t Result = 1;
495 for (; NumSteps; --NumSteps)
496 Result *= Val-(NumSteps-1);
Reid Spencerc5b206b2006-12-31 05:48:39 +0000497 Constant *Res = ConstantInt::get(Type::Int64Ty, Result);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000498 return SCEVUnknown::get(ConstantExpr::getTruncOrBitCast(Res, V->getType()));
Chris Lattner53e677a2004-04-02 20:23:17 +0000499 }
500
501 const Type *Ty = V->getType();
502 if (NumSteps == 0)
Chris Lattnerb06432c2004-04-23 21:29:03 +0000503 return SCEVUnknown::getIntegerSCEV(1, Ty);
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000504
Chris Lattner53e677a2004-04-02 20:23:17 +0000505 SCEVHandle Result = V;
506 for (unsigned i = 1; i != NumSteps; ++i)
Chris Lattnerbac5b462005-03-09 05:34:41 +0000507 Result = SCEVMulExpr::get(Result, SCEV::getMinusSCEV(V,
Chris Lattnerb06432c2004-04-23 21:29:03 +0000508 SCEVUnknown::getIntegerSCEV(i, Ty)));
Chris Lattner53e677a2004-04-02 20:23:17 +0000509 return Result;
510}
511
512
513/// evaluateAtIteration - Return the value of this chain of recurrences at
514/// the specified iteration number. We can evaluate this recurrence by
515/// multiplying each element in the chain by the binomial coefficient
516/// corresponding to it. In other words, we can evaluate {A,+,B,+,C,+,D} as:
517///
518/// A*choose(It, 0) + B*choose(It, 1) + C*choose(It, 2) + D*choose(It, 3)
519///
520/// FIXME/VERIFY: I don't trust that this is correct in the face of overflow.
521/// Is the binomial equation safe using modular arithmetic??
522///
523SCEVHandle SCEVAddRecExpr::evaluateAtIteration(SCEVHandle It) const {
524 SCEVHandle Result = getStart();
525 int Divisor = 1;
526 const Type *Ty = It->getType();
527 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
528 SCEVHandle BC = PartialFact(It, i);
529 Divisor *= i;
Chris Lattner60a05cc2006-04-01 04:48:52 +0000530 SCEVHandle Val = SCEVSDivExpr::get(SCEVMulExpr::get(BC, getOperand(i)),
Chris Lattnerb06432c2004-04-23 21:29:03 +0000531 SCEVUnknown::getIntegerSCEV(Divisor,Ty));
Chris Lattner53e677a2004-04-02 20:23:17 +0000532 Result = SCEVAddExpr::get(Result, Val);
533 }
534 return Result;
535}
536
537
538//===----------------------------------------------------------------------===//
539// SCEV Expression folder implementations
540//===----------------------------------------------------------------------===//
541
542SCEVHandle SCEVTruncateExpr::get(const SCEVHandle &Op, const Type *Ty) {
543 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
Reid Spencer7858b332006-12-05 19:14:13 +0000544 return SCEVUnknown::get(
Reid Spencer315d0552006-12-05 22:39:58 +0000545 ConstantExpr::getTrunc(SC->getValue(), Ty));
Chris Lattner53e677a2004-04-02 20:23:17 +0000546
547 // If the input value is a chrec scev made out of constants, truncate
548 // all of the constants.
549 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
550 std::vector<SCEVHandle> Operands;
551 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
552 // FIXME: This should allow truncation of other expression types!
553 if (isa<SCEVConstant>(AddRec->getOperand(i)))
554 Operands.push_back(get(AddRec->getOperand(i), Ty));
555 else
556 break;
557 if (Operands.size() == AddRec->getNumOperands())
558 return SCEVAddRecExpr::get(Operands, AddRec->getLoop());
559 }
560
Chris Lattnerb3364092006-10-04 21:49:37 +0000561 SCEVTruncateExpr *&Result = (*SCEVTruncates)[std::make_pair(Op, Ty)];
Chris Lattner53e677a2004-04-02 20:23:17 +0000562 if (Result == 0) Result = new SCEVTruncateExpr(Op, Ty);
563 return Result;
564}
565
566SCEVHandle SCEVZeroExtendExpr::get(const SCEVHandle &Op, const Type *Ty) {
567 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
Reid Spencer7858b332006-12-05 19:14:13 +0000568 return SCEVUnknown::get(
Reid Spencerd977d862006-12-12 23:36:14 +0000569 ConstantExpr::getZExt(SC->getValue(), Ty));
Chris Lattner53e677a2004-04-02 20:23:17 +0000570
571 // FIXME: If the input value is a chrec scev, and we can prove that the value
572 // did not overflow the old, smaller, value, we can zero extend all of the
573 // operands (often constants). This would allow analysis of something like
574 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
575
Chris Lattnerb3364092006-10-04 21:49:37 +0000576 SCEVZeroExtendExpr *&Result = (*SCEVZeroExtends)[std::make_pair(Op, Ty)];
Chris Lattner53e677a2004-04-02 20:23:17 +0000577 if (Result == 0) Result = new SCEVZeroExtendExpr(Op, Ty);
578 return Result;
579}
580
581// get - Get a canonical add expression, or something simpler if possible.
582SCEVHandle SCEVAddExpr::get(std::vector<SCEVHandle> &Ops) {
583 assert(!Ops.empty() && "Cannot get empty add!");
Chris Lattner627018b2004-04-07 16:16:11 +0000584 if (Ops.size() == 1) return Ops[0];
Chris Lattner53e677a2004-04-02 20:23:17 +0000585
586 // Sort by complexity, this groups all similar expression types together.
Chris Lattner8d741b82004-06-20 06:23:15 +0000587 GroupByComplexity(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +0000588
589 // If there are any constants, fold them together.
590 unsigned Idx = 0;
591 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
592 ++Idx;
Chris Lattner627018b2004-04-07 16:16:11 +0000593 assert(Idx < Ops.size());
Chris Lattner53e677a2004-04-02 20:23:17 +0000594 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
595 // We found two constants, fold them together!
596 Constant *Fold = ConstantExpr::getAdd(LHSC->getValue(), RHSC->getValue());
597 if (ConstantInt *CI = dyn_cast<ConstantInt>(Fold)) {
598 Ops[0] = SCEVConstant::get(CI);
599 Ops.erase(Ops.begin()+1); // Erase the folded element
600 if (Ops.size() == 1) return Ops[0];
Chris Lattner7ffc07d2005-02-26 18:50:19 +0000601 LHSC = cast<SCEVConstant>(Ops[0]);
Chris Lattner53e677a2004-04-02 20:23:17 +0000602 } else {
603 // If we couldn't fold the expression, move to the next constant. Note
604 // that this is impossible to happen in practice because we always
605 // constant fold constant ints to constant ints.
606 ++Idx;
607 }
608 }
609
610 // If we are left with a constant zero being added, strip it off.
611 if (cast<SCEVConstant>(Ops[0])->getValue()->isNullValue()) {
612 Ops.erase(Ops.begin());
613 --Idx;
614 }
615 }
616
Chris Lattner627018b2004-04-07 16:16:11 +0000617 if (Ops.size() == 1) return Ops[0];
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000618
Chris Lattner53e677a2004-04-02 20:23:17 +0000619 // Okay, check to see if the same value occurs in the operand list twice. If
620 // so, merge them together into an multiply expression. Since we sorted the
621 // list, these values are required to be adjacent.
622 const Type *Ty = Ops[0]->getType();
623 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
624 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
625 // Found a match, merge the two values into a multiply, and add any
626 // remaining values to the result.
Chris Lattnerb06432c2004-04-23 21:29:03 +0000627 SCEVHandle Two = SCEVUnknown::getIntegerSCEV(2, Ty);
Chris Lattner53e677a2004-04-02 20:23:17 +0000628 SCEVHandle Mul = SCEVMulExpr::get(Ops[i], Two);
629 if (Ops.size() == 2)
630 return Mul;
631 Ops.erase(Ops.begin()+i, Ops.begin()+i+2);
632 Ops.push_back(Mul);
633 return SCEVAddExpr::get(Ops);
634 }
635
636 // Okay, now we know the first non-constant operand. If there are add
637 // operands they would be next.
638 if (Idx < Ops.size()) {
639 bool DeletedAdd = false;
640 while (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
641 // If we have an add, expand the add operands onto the end of the operands
642 // list.
643 Ops.insert(Ops.end(), Add->op_begin(), Add->op_end());
644 Ops.erase(Ops.begin()+Idx);
645 DeletedAdd = true;
646 }
647
648 // If we deleted at least one add, we added operands to the end of the list,
649 // and they are not necessarily sorted. Recurse to resort and resimplify
650 // any operands we just aquired.
651 if (DeletedAdd)
652 return get(Ops);
653 }
654
655 // Skip over the add expression until we get to a multiply.
656 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
657 ++Idx;
658
659 // If we are adding something to a multiply expression, make sure the
660 // something is not already an operand of the multiply. If so, merge it into
661 // the multiply.
662 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
663 SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
664 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
665 SCEV *MulOpSCEV = Mul->getOperand(MulOp);
666 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
Chris Lattner6a1a78a2004-12-04 20:54:32 +0000667 if (MulOpSCEV == Ops[AddOp] && !isa<SCEVConstant>(MulOpSCEV)) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000668 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
669 SCEVHandle InnerMul = Mul->getOperand(MulOp == 0);
670 if (Mul->getNumOperands() != 2) {
671 // If the multiply has more than two operands, we must get the
672 // Y*Z term.
673 std::vector<SCEVHandle> MulOps(Mul->op_begin(), Mul->op_end());
674 MulOps.erase(MulOps.begin()+MulOp);
675 InnerMul = SCEVMulExpr::get(MulOps);
676 }
Chris Lattnerb06432c2004-04-23 21:29:03 +0000677 SCEVHandle One = SCEVUnknown::getIntegerSCEV(1, Ty);
Chris Lattner53e677a2004-04-02 20:23:17 +0000678 SCEVHandle AddOne = SCEVAddExpr::get(InnerMul, One);
679 SCEVHandle OuterMul = SCEVMulExpr::get(AddOne, Ops[AddOp]);
680 if (Ops.size() == 2) return OuterMul;
681 if (AddOp < Idx) {
682 Ops.erase(Ops.begin()+AddOp);
683 Ops.erase(Ops.begin()+Idx-1);
684 } else {
685 Ops.erase(Ops.begin()+Idx);
686 Ops.erase(Ops.begin()+AddOp-1);
687 }
688 Ops.push_back(OuterMul);
689 return SCEVAddExpr::get(Ops);
690 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000691
Chris Lattner53e677a2004-04-02 20:23:17 +0000692 // Check this multiply against other multiplies being added together.
693 for (unsigned OtherMulIdx = Idx+1;
694 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
695 ++OtherMulIdx) {
696 SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
697 // If MulOp occurs in OtherMul, we can fold the two multiplies
698 // together.
699 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
700 OMulOp != e; ++OMulOp)
701 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
702 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
703 SCEVHandle InnerMul1 = Mul->getOperand(MulOp == 0);
704 if (Mul->getNumOperands() != 2) {
705 std::vector<SCEVHandle> MulOps(Mul->op_begin(), Mul->op_end());
706 MulOps.erase(MulOps.begin()+MulOp);
707 InnerMul1 = SCEVMulExpr::get(MulOps);
708 }
709 SCEVHandle InnerMul2 = OtherMul->getOperand(OMulOp == 0);
710 if (OtherMul->getNumOperands() != 2) {
711 std::vector<SCEVHandle> MulOps(OtherMul->op_begin(),
712 OtherMul->op_end());
713 MulOps.erase(MulOps.begin()+OMulOp);
714 InnerMul2 = SCEVMulExpr::get(MulOps);
715 }
716 SCEVHandle InnerMulSum = SCEVAddExpr::get(InnerMul1,InnerMul2);
717 SCEVHandle OuterMul = SCEVMulExpr::get(MulOpSCEV, InnerMulSum);
718 if (Ops.size() == 2) return OuterMul;
719 Ops.erase(Ops.begin()+Idx);
720 Ops.erase(Ops.begin()+OtherMulIdx-1);
721 Ops.push_back(OuterMul);
722 return SCEVAddExpr::get(Ops);
723 }
724 }
725 }
726 }
727
728 // If there are any add recurrences in the operands list, see if any other
729 // added values are loop invariant. If so, we can fold them into the
730 // recurrence.
731 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
732 ++Idx;
733
734 // Scan over all recurrences, trying to fold loop invariants into them.
735 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
736 // Scan all of the other operands to this add and add them to the vector if
737 // they are loop invariant w.r.t. the recurrence.
738 std::vector<SCEVHandle> LIOps;
739 SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
740 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
741 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
742 LIOps.push_back(Ops[i]);
743 Ops.erase(Ops.begin()+i);
744 --i; --e;
745 }
746
747 // If we found some loop invariants, fold them into the recurrence.
748 if (!LIOps.empty()) {
749 // NLI + LI + { Start,+,Step} --> NLI + { LI+Start,+,Step }
750 LIOps.push_back(AddRec->getStart());
751
752 std::vector<SCEVHandle> AddRecOps(AddRec->op_begin(), AddRec->op_end());
753 AddRecOps[0] = SCEVAddExpr::get(LIOps);
754
755 SCEVHandle NewRec = SCEVAddRecExpr::get(AddRecOps, AddRec->getLoop());
756 // If all of the other operands were loop invariant, we are done.
757 if (Ops.size() == 1) return NewRec;
758
759 // Otherwise, add the folded AddRec by the non-liv parts.
760 for (unsigned i = 0;; ++i)
761 if (Ops[i] == AddRec) {
762 Ops[i] = NewRec;
763 break;
764 }
765 return SCEVAddExpr::get(Ops);
766 }
767
768 // Okay, if there weren't any loop invariants to be folded, check to see if
769 // there are multiple AddRec's with the same loop induction variable being
770 // added together. If so, we can fold them.
771 for (unsigned OtherIdx = Idx+1;
772 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
773 if (OtherIdx != Idx) {
774 SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
775 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
776 // Other + {A,+,B} + {C,+,D} --> Other + {A+C,+,B+D}
777 std::vector<SCEVHandle> NewOps(AddRec->op_begin(), AddRec->op_end());
778 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); i != e; ++i) {
779 if (i >= NewOps.size()) {
780 NewOps.insert(NewOps.end(), OtherAddRec->op_begin()+i,
781 OtherAddRec->op_end());
782 break;
783 }
784 NewOps[i] = SCEVAddExpr::get(NewOps[i], OtherAddRec->getOperand(i));
785 }
786 SCEVHandle NewAddRec = SCEVAddRecExpr::get(NewOps, AddRec->getLoop());
787
788 if (Ops.size() == 2) return NewAddRec;
789
790 Ops.erase(Ops.begin()+Idx);
791 Ops.erase(Ops.begin()+OtherIdx-1);
792 Ops.push_back(NewAddRec);
793 return SCEVAddExpr::get(Ops);
794 }
795 }
796
797 // Otherwise couldn't fold anything into this recurrence. Move onto the
798 // next one.
799 }
800
801 // Okay, it looks like we really DO need an add expr. Check to see if we
802 // already have one, otherwise create a new one.
803 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
Chris Lattnerb3364092006-10-04 21:49:37 +0000804 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scAddExpr,
805 SCEVOps)];
Chris Lattner53e677a2004-04-02 20:23:17 +0000806 if (Result == 0) Result = new SCEVAddExpr(Ops);
807 return Result;
808}
809
810
811SCEVHandle SCEVMulExpr::get(std::vector<SCEVHandle> &Ops) {
812 assert(!Ops.empty() && "Cannot get empty mul!");
813
814 // Sort by complexity, this groups all similar expression types together.
Chris Lattner8d741b82004-06-20 06:23:15 +0000815 GroupByComplexity(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +0000816
817 // If there are any constants, fold them together.
818 unsigned Idx = 0;
819 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
820
821 // C1*(C2+V) -> C1*C2 + C1*V
822 if (Ops.size() == 2)
823 if (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
824 if (Add->getNumOperands() == 2 &&
825 isa<SCEVConstant>(Add->getOperand(0)))
826 return SCEVAddExpr::get(SCEVMulExpr::get(LHSC, Add->getOperand(0)),
827 SCEVMulExpr::get(LHSC, Add->getOperand(1)));
828
829
830 ++Idx;
831 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
832 // We found two constants, fold them together!
833 Constant *Fold = ConstantExpr::getMul(LHSC->getValue(), RHSC->getValue());
834 if (ConstantInt *CI = dyn_cast<ConstantInt>(Fold)) {
835 Ops[0] = SCEVConstant::get(CI);
836 Ops.erase(Ops.begin()+1); // Erase the folded element
837 if (Ops.size() == 1) return Ops[0];
Chris Lattner7ffc07d2005-02-26 18:50:19 +0000838 LHSC = cast<SCEVConstant>(Ops[0]);
Chris Lattner53e677a2004-04-02 20:23:17 +0000839 } else {
840 // If we couldn't fold the expression, move to the next constant. Note
841 // that this is impossible to happen in practice because we always
842 // constant fold constant ints to constant ints.
843 ++Idx;
844 }
845 }
846
847 // If we are left with a constant one being multiplied, strip it off.
848 if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) {
849 Ops.erase(Ops.begin());
850 --Idx;
851 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isNullValue()) {
852 // If we have a multiply of zero, it will always be zero.
853 return Ops[0];
854 }
855 }
856
857 // Skip over the add expression until we get to a multiply.
858 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
859 ++Idx;
860
861 if (Ops.size() == 1)
862 return Ops[0];
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000863
Chris Lattner53e677a2004-04-02 20:23:17 +0000864 // If there are mul operands inline them all into this expression.
865 if (Idx < Ops.size()) {
866 bool DeletedMul = false;
867 while (SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
868 // If we have an mul, expand the mul operands onto the end of the operands
869 // list.
870 Ops.insert(Ops.end(), Mul->op_begin(), Mul->op_end());
871 Ops.erase(Ops.begin()+Idx);
872 DeletedMul = true;
873 }
874
875 // If we deleted at least one mul, we added operands to the end of the list,
876 // and they are not necessarily sorted. Recurse to resort and resimplify
877 // any operands we just aquired.
878 if (DeletedMul)
879 return get(Ops);
880 }
881
882 // If there are any add recurrences in the operands list, see if any other
883 // added values are loop invariant. If so, we can fold them into the
884 // recurrence.
885 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
886 ++Idx;
887
888 // Scan over all recurrences, trying to fold loop invariants into them.
889 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
890 // Scan all of the other operands to this mul and add them to the vector if
891 // they are loop invariant w.r.t. the recurrence.
892 std::vector<SCEVHandle> LIOps;
893 SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
894 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
895 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
896 LIOps.push_back(Ops[i]);
897 Ops.erase(Ops.begin()+i);
898 --i; --e;
899 }
900
901 // If we found some loop invariants, fold them into the recurrence.
902 if (!LIOps.empty()) {
903 // NLI * LI * { Start,+,Step} --> NLI * { LI*Start,+,LI*Step }
904 std::vector<SCEVHandle> NewOps;
905 NewOps.reserve(AddRec->getNumOperands());
906 if (LIOps.size() == 1) {
907 SCEV *Scale = LIOps[0];
908 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
909 NewOps.push_back(SCEVMulExpr::get(Scale, AddRec->getOperand(i)));
910 } else {
911 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
912 std::vector<SCEVHandle> MulOps(LIOps);
913 MulOps.push_back(AddRec->getOperand(i));
914 NewOps.push_back(SCEVMulExpr::get(MulOps));
915 }
916 }
917
918 SCEVHandle NewRec = SCEVAddRecExpr::get(NewOps, AddRec->getLoop());
919
920 // If all of the other operands were loop invariant, we are done.
921 if (Ops.size() == 1) return NewRec;
922
923 // Otherwise, multiply the folded AddRec by the non-liv parts.
924 for (unsigned i = 0;; ++i)
925 if (Ops[i] == AddRec) {
926 Ops[i] = NewRec;
927 break;
928 }
929 return SCEVMulExpr::get(Ops);
930 }
931
932 // Okay, if there weren't any loop invariants to be folded, check to see if
933 // there are multiple AddRec's with the same loop induction variable being
934 // multiplied together. If so, we can fold them.
935 for (unsigned OtherIdx = Idx+1;
936 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
937 if (OtherIdx != Idx) {
938 SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
939 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
940 // F * G --> {A,+,B} * {C,+,D} --> {A*C,+,F*D + G*B + B*D}
941 SCEVAddRecExpr *F = AddRec, *G = OtherAddRec;
942 SCEVHandle NewStart = SCEVMulExpr::get(F->getStart(),
943 G->getStart());
944 SCEVHandle B = F->getStepRecurrence();
945 SCEVHandle D = G->getStepRecurrence();
946 SCEVHandle NewStep = SCEVAddExpr::get(SCEVMulExpr::get(F, D),
947 SCEVMulExpr::get(G, B),
948 SCEVMulExpr::get(B, D));
949 SCEVHandle NewAddRec = SCEVAddRecExpr::get(NewStart, NewStep,
950 F->getLoop());
951 if (Ops.size() == 2) return NewAddRec;
952
953 Ops.erase(Ops.begin()+Idx);
954 Ops.erase(Ops.begin()+OtherIdx-1);
955 Ops.push_back(NewAddRec);
956 return SCEVMulExpr::get(Ops);
957 }
958 }
959
960 // Otherwise couldn't fold anything into this recurrence. Move onto the
961 // next one.
962 }
963
964 // Okay, it looks like we really DO need an mul expr. Check to see if we
965 // already have one, otherwise create a new one.
966 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
Chris Lattnerb3364092006-10-04 21:49:37 +0000967 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scMulExpr,
968 SCEVOps)];
Chris Lattner6a1a78a2004-12-04 20:54:32 +0000969 if (Result == 0)
970 Result = new SCEVMulExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +0000971 return Result;
972}
973
Chris Lattner60a05cc2006-04-01 04:48:52 +0000974SCEVHandle SCEVSDivExpr::get(const SCEVHandle &LHS, const SCEVHandle &RHS) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000975 if (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
976 if (RHSC->getValue()->equalsInt(1))
Reid Spencer1628cec2006-10-26 06:15:43 +0000977 return LHS; // X sdiv 1 --> x
Chris Lattner53e677a2004-04-02 20:23:17 +0000978 if (RHSC->getValue()->isAllOnesValue())
Reid Spencer1628cec2006-10-26 06:15:43 +0000979 return SCEV::getNegativeSCEV(LHS); // X sdiv -1 --> -x
Chris Lattner53e677a2004-04-02 20:23:17 +0000980
981 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
982 Constant *LHSCV = LHSC->getValue();
983 Constant *RHSCV = RHSC->getValue();
Reid Spencer1628cec2006-10-26 06:15:43 +0000984 return SCEVUnknown::get(ConstantExpr::getSDiv(LHSCV, RHSCV));
Chris Lattner53e677a2004-04-02 20:23:17 +0000985 }
986 }
987
988 // FIXME: implement folding of (X*4)/4 when we know X*4 doesn't overflow.
989
Chris Lattnerb3364092006-10-04 21:49:37 +0000990 SCEVSDivExpr *&Result = (*SCEVSDivs)[std::make_pair(LHS, RHS)];
Chris Lattner60a05cc2006-04-01 04:48:52 +0000991 if (Result == 0) Result = new SCEVSDivExpr(LHS, RHS);
Chris Lattner53e677a2004-04-02 20:23:17 +0000992 return Result;
993}
994
995
996/// SCEVAddRecExpr::get - Get a add recurrence expression for the
997/// specified loop. Simplify the expression as much as possible.
998SCEVHandle SCEVAddRecExpr::get(const SCEVHandle &Start,
999 const SCEVHandle &Step, const Loop *L) {
1000 std::vector<SCEVHandle> Operands;
1001 Operands.push_back(Start);
1002 if (SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
1003 if (StepChrec->getLoop() == L) {
1004 Operands.insert(Operands.end(), StepChrec->op_begin(),
1005 StepChrec->op_end());
1006 return get(Operands, L);
1007 }
1008
1009 Operands.push_back(Step);
1010 return get(Operands, L);
1011}
1012
1013/// SCEVAddRecExpr::get - Get a add recurrence expression for the
1014/// specified loop. Simplify the expression as much as possible.
1015SCEVHandle SCEVAddRecExpr::get(std::vector<SCEVHandle> &Operands,
1016 const Loop *L) {
1017 if (Operands.size() == 1) return Operands[0];
1018
1019 if (SCEVConstant *StepC = dyn_cast<SCEVConstant>(Operands.back()))
1020 if (StepC->getValue()->isNullValue()) {
1021 Operands.pop_back();
1022 return get(Operands, L); // { X,+,0 } --> X
1023 }
1024
1025 SCEVAddRecExpr *&Result =
Chris Lattnerb3364092006-10-04 21:49:37 +00001026 (*SCEVAddRecExprs)[std::make_pair(L, std::vector<SCEV*>(Operands.begin(),
1027 Operands.end()))];
Chris Lattner53e677a2004-04-02 20:23:17 +00001028 if (Result == 0) Result = new SCEVAddRecExpr(Operands, L);
1029 return Result;
1030}
1031
Chris Lattner0a7f98c2004-04-15 15:07:24 +00001032SCEVHandle SCEVUnknown::get(Value *V) {
1033 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
1034 return SCEVConstant::get(CI);
Chris Lattnerb3364092006-10-04 21:49:37 +00001035 SCEVUnknown *&Result = (*SCEVUnknowns)[V];
Chris Lattner0a7f98c2004-04-15 15:07:24 +00001036 if (Result == 0) Result = new SCEVUnknown(V);
1037 return Result;
1038}
1039
Chris Lattner53e677a2004-04-02 20:23:17 +00001040
1041//===----------------------------------------------------------------------===//
Chris Lattner53e677a2004-04-02 20:23:17 +00001042// ScalarEvolutionsImpl Definition and Implementation
1043//===----------------------------------------------------------------------===//
1044//
1045/// ScalarEvolutionsImpl - This class implements the main driver for the scalar
1046/// evolution code.
1047///
1048namespace {
Chris Lattner95255282006-06-28 23:17:24 +00001049 struct VISIBILITY_HIDDEN ScalarEvolutionsImpl {
Chris Lattner53e677a2004-04-02 20:23:17 +00001050 /// F - The function we are analyzing.
1051 ///
1052 Function &F;
1053
1054 /// LI - The loop information for the function we are currently analyzing.
1055 ///
1056 LoopInfo &LI;
1057
1058 /// UnknownValue - This SCEV is used to represent unknown trip counts and
1059 /// things.
1060 SCEVHandle UnknownValue;
1061
1062 /// Scalars - This is a cache of the scalars we have analyzed so far.
1063 ///
1064 std::map<Value*, SCEVHandle> Scalars;
1065
1066 /// IterationCounts - Cache the iteration count of the loops for this
1067 /// function as they are computed.
1068 std::map<const Loop*, SCEVHandle> IterationCounts;
1069
Chris Lattner3221ad02004-04-17 22:58:41 +00001070 /// ConstantEvolutionLoopExitValue - This map contains entries for all of
1071 /// the PHI instructions that we attempt to compute constant evolutions for.
1072 /// This allows us to avoid potentially expensive recomputation of these
1073 /// properties. An instruction maps to null if we are unable to compute its
1074 /// exit value.
1075 std::map<PHINode*, Constant*> ConstantEvolutionLoopExitValue;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001076
Chris Lattner53e677a2004-04-02 20:23:17 +00001077 public:
1078 ScalarEvolutionsImpl(Function &f, LoopInfo &li)
1079 : F(f), LI(li), UnknownValue(new SCEVCouldNotCompute()) {}
1080
1081 /// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
1082 /// expression and create a new one.
1083 SCEVHandle getSCEV(Value *V);
1084
Chris Lattnera0740fb2005-08-09 23:36:33 +00001085 /// hasSCEV - Return true if the SCEV for this value has already been
1086 /// computed.
1087 bool hasSCEV(Value *V) const {
1088 return Scalars.count(V);
1089 }
1090
1091 /// setSCEV - Insert the specified SCEV into the map of current SCEVs for
1092 /// the specified value.
1093 void setSCEV(Value *V, const SCEVHandle &H) {
1094 bool isNew = Scalars.insert(std::make_pair(V, H)).second;
1095 assert(isNew && "This entry already existed!");
1096 }
1097
1098
Chris Lattner53e677a2004-04-02 20:23:17 +00001099 /// getSCEVAtScope - Compute the value of the specified expression within
1100 /// the indicated loop (which may be null to indicate in no loop). If the
1101 /// expression cannot be evaluated, return UnknownValue itself.
1102 SCEVHandle getSCEVAtScope(SCEV *V, const Loop *L);
1103
1104
1105 /// hasLoopInvariantIterationCount - Return true if the specified loop has
1106 /// an analyzable loop-invariant iteration count.
1107 bool hasLoopInvariantIterationCount(const Loop *L);
1108
1109 /// getIterationCount - If the specified loop has a predictable iteration
1110 /// count, return it. Note that it is not valid to call this method on a
1111 /// loop without a loop-invariant iteration count.
1112 SCEVHandle getIterationCount(const Loop *L);
1113
1114 /// deleteInstructionFromRecords - This method should be called by the
1115 /// client before it removes an instruction from the program, to make sure
1116 /// that no dangling references are left around.
1117 void deleteInstructionFromRecords(Instruction *I);
1118
1119 private:
1120 /// createSCEV - We know that there is no SCEV for the specified value.
1121 /// Analyze the expression.
1122 SCEVHandle createSCEV(Value *V);
Chris Lattner53e677a2004-04-02 20:23:17 +00001123
1124 /// createNodeForPHI - Provide the special handling we need to analyze PHI
1125 /// SCEVs.
1126 SCEVHandle createNodeForPHI(PHINode *PN);
Chris Lattner4dc534c2005-02-13 04:37:18 +00001127
1128 /// ReplaceSymbolicValueWithConcrete - This looks up the computed SCEV value
1129 /// for the specified instruction and replaces any references to the
1130 /// symbolic value SymName with the specified value. This is used during
1131 /// PHI resolution.
1132 void ReplaceSymbolicValueWithConcrete(Instruction *I,
1133 const SCEVHandle &SymName,
1134 const SCEVHandle &NewVal);
Chris Lattner53e677a2004-04-02 20:23:17 +00001135
1136 /// ComputeIterationCount - Compute the number of times the specified loop
1137 /// will iterate.
1138 SCEVHandle ComputeIterationCount(const Loop *L);
1139
Chris Lattner673e02b2004-10-12 01:49:27 +00001140 /// ComputeLoadConstantCompareIterationCount - Given an exit condition of
1141 /// 'setcc load X, cst', try to se if we can compute the trip count.
1142 SCEVHandle ComputeLoadConstantCompareIterationCount(LoadInst *LI,
1143 Constant *RHS,
1144 const Loop *L,
Reid Spencere4d87aa2006-12-23 06:05:41 +00001145 ICmpInst::Predicate p);
Chris Lattner673e02b2004-10-12 01:49:27 +00001146
Chris Lattner7980fb92004-04-17 18:36:24 +00001147 /// ComputeIterationCountExhaustively - If the trip is known to execute a
1148 /// constant number of times (the condition evolves only from constants),
1149 /// try to evaluate a few iterations of the loop until we get the exit
1150 /// condition gets a value of ExitWhen (true or false). If we cannot
1151 /// evaluate the trip count of the loop, return UnknownValue.
1152 SCEVHandle ComputeIterationCountExhaustively(const Loop *L, Value *Cond,
1153 bool ExitWhen);
1154
Chris Lattner53e677a2004-04-02 20:23:17 +00001155 /// HowFarToZero - Return the number of times a backedge comparing the
1156 /// specified value to zero will execute. If not computable, return
Chris Lattnerdb25de42005-08-15 23:33:51 +00001157 /// UnknownValue.
Chris Lattner53e677a2004-04-02 20:23:17 +00001158 SCEVHandle HowFarToZero(SCEV *V, const Loop *L);
1159
1160 /// HowFarToNonZero - Return the number of times a backedge checking the
1161 /// specified value for nonzero will execute. If not computable, return
Chris Lattnerdb25de42005-08-15 23:33:51 +00001162 /// UnknownValue.
Chris Lattner53e677a2004-04-02 20:23:17 +00001163 SCEVHandle HowFarToNonZero(SCEV *V, const Loop *L);
Chris Lattner3221ad02004-04-17 22:58:41 +00001164
Chris Lattnerdb25de42005-08-15 23:33:51 +00001165 /// HowManyLessThans - Return the number of times a backedge containing the
1166 /// specified less-than comparison will execute. If not computable, return
1167 /// UnknownValue.
1168 SCEVHandle HowManyLessThans(SCEV *LHS, SCEV *RHS, const Loop *L);
1169
Chris Lattner3221ad02004-04-17 22:58:41 +00001170 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
1171 /// in the header of its containing loop, we know the loop executes a
1172 /// constant number of times, and the PHI node is just a recurrence
1173 /// involving constants, fold it.
1174 Constant *getConstantEvolutionLoopExitValue(PHINode *PN, uint64_t Its,
1175 const Loop *L);
Chris Lattner53e677a2004-04-02 20:23:17 +00001176 };
1177}
1178
1179//===----------------------------------------------------------------------===//
1180// Basic SCEV Analysis and PHI Idiom Recognition Code
1181//
1182
1183/// deleteInstructionFromRecords - This method should be called by the
1184/// client before it removes an instruction from the program, to make sure
1185/// that no dangling references are left around.
1186void ScalarEvolutionsImpl::deleteInstructionFromRecords(Instruction *I) {
1187 Scalars.erase(I);
Chris Lattner3221ad02004-04-17 22:58:41 +00001188 if (PHINode *PN = dyn_cast<PHINode>(I))
1189 ConstantEvolutionLoopExitValue.erase(PN);
Chris Lattner53e677a2004-04-02 20:23:17 +00001190}
1191
1192
1193/// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
1194/// expression and create a new one.
1195SCEVHandle ScalarEvolutionsImpl::getSCEV(Value *V) {
1196 assert(V->getType() != Type::VoidTy && "Can't analyze void expressions!");
1197
1198 std::map<Value*, SCEVHandle>::iterator I = Scalars.find(V);
1199 if (I != Scalars.end()) return I->second;
1200 SCEVHandle S = createSCEV(V);
1201 Scalars.insert(std::make_pair(V, S));
1202 return S;
1203}
1204
Chris Lattner4dc534c2005-02-13 04:37:18 +00001205/// ReplaceSymbolicValueWithConcrete - This looks up the computed SCEV value for
1206/// the specified instruction and replaces any references to the symbolic value
1207/// SymName with the specified value. This is used during PHI resolution.
1208void ScalarEvolutionsImpl::
1209ReplaceSymbolicValueWithConcrete(Instruction *I, const SCEVHandle &SymName,
1210 const SCEVHandle &NewVal) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001211 std::map<Value*, SCEVHandle>::iterator SI = Scalars.find(I);
Chris Lattner4dc534c2005-02-13 04:37:18 +00001212 if (SI == Scalars.end()) return;
Chris Lattner53e677a2004-04-02 20:23:17 +00001213
Chris Lattner4dc534c2005-02-13 04:37:18 +00001214 SCEVHandle NV =
1215 SI->second->replaceSymbolicValuesWithConcrete(SymName, NewVal);
1216 if (NV == SI->second) return; // No change.
1217
1218 SI->second = NV; // Update the scalars map!
1219
1220 // Any instruction values that use this instruction might also need to be
1221 // updated!
1222 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1223 UI != E; ++UI)
1224 ReplaceSymbolicValueWithConcrete(cast<Instruction>(*UI), SymName, NewVal);
1225}
Chris Lattner53e677a2004-04-02 20:23:17 +00001226
1227/// createNodeForPHI - PHI nodes have two cases. Either the PHI node exists in
1228/// a loop header, making it a potential recurrence, or it doesn't.
1229///
1230SCEVHandle ScalarEvolutionsImpl::createNodeForPHI(PHINode *PN) {
1231 if (PN->getNumIncomingValues() == 2) // The loops have been canonicalized.
1232 if (const Loop *L = LI.getLoopFor(PN->getParent()))
1233 if (L->getHeader() == PN->getParent()) {
1234 // If it lives in the loop header, it has two incoming values, one
1235 // from outside the loop, and one from inside.
1236 unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0));
1237 unsigned BackEdge = IncomingEdge^1;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001238
Chris Lattner53e677a2004-04-02 20:23:17 +00001239 // While we are analyzing this PHI node, handle its value symbolically.
1240 SCEVHandle SymbolicName = SCEVUnknown::get(PN);
1241 assert(Scalars.find(PN) == Scalars.end() &&
1242 "PHI node already processed?");
1243 Scalars.insert(std::make_pair(PN, SymbolicName));
1244
1245 // Using this symbolic name for the PHI, analyze the value coming around
1246 // the back-edge.
1247 SCEVHandle BEValue = getSCEV(PN->getIncomingValue(BackEdge));
1248
1249 // NOTE: If BEValue is loop invariant, we know that the PHI node just
1250 // has a special value for the first iteration of the loop.
1251
1252 // If the value coming around the backedge is an add with the symbolic
1253 // value we just inserted, then we found a simple induction variable!
1254 if (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
1255 // If there is a single occurrence of the symbolic value, replace it
1256 // with a recurrence.
1257 unsigned FoundIndex = Add->getNumOperands();
1258 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
1259 if (Add->getOperand(i) == SymbolicName)
1260 if (FoundIndex == e) {
1261 FoundIndex = i;
1262 break;
1263 }
1264
1265 if (FoundIndex != Add->getNumOperands()) {
1266 // Create an add with everything but the specified operand.
1267 std::vector<SCEVHandle> Ops;
1268 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
1269 if (i != FoundIndex)
1270 Ops.push_back(Add->getOperand(i));
1271 SCEVHandle Accum = SCEVAddExpr::get(Ops);
1272
1273 // This is not a valid addrec if the step amount is varying each
1274 // loop iteration, but is not itself an addrec in this loop.
1275 if (Accum->isLoopInvariant(L) ||
1276 (isa<SCEVAddRecExpr>(Accum) &&
1277 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
1278 SCEVHandle StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
1279 SCEVHandle PHISCEV = SCEVAddRecExpr::get(StartVal, Accum, L);
1280
1281 // Okay, for the entire analysis of this edge we assumed the PHI
1282 // to be symbolic. We now need to go back and update all of the
1283 // entries for the scalars that use the PHI (except for the PHI
1284 // itself) to use the new analyzed value instead of the "symbolic"
1285 // value.
Chris Lattner4dc534c2005-02-13 04:37:18 +00001286 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
Chris Lattner53e677a2004-04-02 20:23:17 +00001287 return PHISCEV;
1288 }
1289 }
Chris Lattner97156e72006-04-26 18:34:07 +00001290 } else if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(BEValue)) {
1291 // Otherwise, this could be a loop like this:
1292 // i = 0; for (j = 1; ..; ++j) { .... i = j; }
1293 // In this case, j = {1,+,1} and BEValue is j.
1294 // Because the other in-value of i (0) fits the evolution of BEValue
1295 // i really is an addrec evolution.
1296 if (AddRec->getLoop() == L && AddRec->isAffine()) {
1297 SCEVHandle StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
1298
1299 // If StartVal = j.start - j.stride, we can use StartVal as the
1300 // initial step of the addrec evolution.
1301 if (StartVal == SCEV::getMinusSCEV(AddRec->getOperand(0),
1302 AddRec->getOperand(1))) {
1303 SCEVHandle PHISCEV =
1304 SCEVAddRecExpr::get(StartVal, AddRec->getOperand(1), L);
1305
1306 // Okay, for the entire analysis of this edge we assumed the PHI
1307 // to be symbolic. We now need to go back and update all of the
1308 // entries for the scalars that use the PHI (except for the PHI
1309 // itself) to use the new analyzed value instead of the "symbolic"
1310 // value.
1311 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
1312 return PHISCEV;
1313 }
1314 }
Chris Lattner53e677a2004-04-02 20:23:17 +00001315 }
1316
1317 return SymbolicName;
1318 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001319
Chris Lattner53e677a2004-04-02 20:23:17 +00001320 // If it's not a loop phi, we can't handle it yet.
1321 return SCEVUnknown::get(PN);
1322}
1323
Chris Lattnera17f0392006-12-12 02:26:09 +00001324/// GetConstantFactor - Determine the largest constant factor that S has. For
1325/// example, turn {4,+,8} -> 4. (S umod result) should always equal zero.
1326static uint64_t GetConstantFactor(SCEVHandle S) {
1327 if (SCEVConstant *C = dyn_cast<SCEVConstant>(S)) {
1328 if (uint64_t V = C->getValue()->getZExtValue())
1329 return V;
1330 else // Zero is a multiple of everything.
1331 return 1ULL << (S->getType()->getPrimitiveSizeInBits()-1);
1332 }
1333
1334 if (SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
1335 return GetConstantFactor(T->getOperand()) &
Chris Lattner42a75512007-01-15 02:27:26 +00001336 T->getType()->getIntegerTypeMask();
Chris Lattnera17f0392006-12-12 02:26:09 +00001337 if (SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S))
1338 return GetConstantFactor(E->getOperand());
1339
1340 if (SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
1341 // The result is the min of all operands.
1342 uint64_t Res = GetConstantFactor(A->getOperand(0));
1343 for (unsigned i = 1, e = A->getNumOperands(); i != e && Res > 1; ++i)
1344 Res = std::min(Res, GetConstantFactor(A->getOperand(i)));
1345 return Res;
1346 }
1347
1348 if (SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
1349 // The result is the product of all the operands.
1350 uint64_t Res = GetConstantFactor(M->getOperand(0));
1351 for (unsigned i = 1, e = M->getNumOperands(); i != e; ++i)
1352 Res *= GetConstantFactor(M->getOperand(i));
1353 return Res;
1354 }
1355
1356 if (SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
Chris Lattner75de5ab2006-12-19 01:16:02 +00001357 // For now, we just handle linear expressions.
1358 if (A->getNumOperands() == 2) {
1359 // We want the GCD between the start and the stride value.
1360 uint64_t Start = GetConstantFactor(A->getOperand(0));
1361 if (Start == 1) return 1;
1362 uint64_t Stride = GetConstantFactor(A->getOperand(1));
1363 return GreatestCommonDivisor64(Start, Stride);
1364 }
Chris Lattnera17f0392006-12-12 02:26:09 +00001365 }
1366
1367 // SCEVSDivExpr, SCEVUnknown.
1368 return 1;
1369}
Chris Lattner53e677a2004-04-02 20:23:17 +00001370
1371/// createSCEV - We know that there is no SCEV for the specified value.
1372/// Analyze the expression.
1373///
1374SCEVHandle ScalarEvolutionsImpl::createSCEV(Value *V) {
1375 if (Instruction *I = dyn_cast<Instruction>(V)) {
1376 switch (I->getOpcode()) {
1377 case Instruction::Add:
1378 return SCEVAddExpr::get(getSCEV(I->getOperand(0)),
1379 getSCEV(I->getOperand(1)));
1380 case Instruction::Mul:
1381 return SCEVMulExpr::get(getSCEV(I->getOperand(0)),
1382 getSCEV(I->getOperand(1)));
Reid Spencer1628cec2006-10-26 06:15:43 +00001383 case Instruction::SDiv:
1384 return SCEVSDivExpr::get(getSCEV(I->getOperand(0)),
1385 getSCEV(I->getOperand(1)));
Chris Lattner53e677a2004-04-02 20:23:17 +00001386 break;
1387
1388 case Instruction::Sub:
Chris Lattnerbac5b462005-03-09 05:34:41 +00001389 return SCEV::getMinusSCEV(getSCEV(I->getOperand(0)),
1390 getSCEV(I->getOperand(1)));
Chris Lattnera17f0392006-12-12 02:26:09 +00001391 case Instruction::Or:
1392 // If the RHS of the Or is a constant, we may have something like:
1393 // X*4+1 which got turned into X*4|1. Handle this as an add so loop
1394 // optimizations will transparently handle this case.
1395 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
1396 SCEVHandle LHS = getSCEV(I->getOperand(0));
1397 uint64_t CommonFact = GetConstantFactor(LHS);
1398 assert(CommonFact && "Common factor should at least be 1!");
1399 if (CommonFact > CI->getZExtValue()) {
1400 // If the LHS is a multiple that is larger than the RHS, use +.
1401 return SCEVAddExpr::get(LHS,
1402 getSCEV(I->getOperand(1)));
1403 }
1404 }
1405 break;
1406
Chris Lattner53e677a2004-04-02 20:23:17 +00001407 case Instruction::Shl:
1408 // Turn shift left of a constant amount into a multiply.
1409 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1410 Constant *X = ConstantInt::get(V->getType(), 1);
1411 X = ConstantExpr::getShl(X, SA);
1412 return SCEVMulExpr::get(getSCEV(I->getOperand(0)), getSCEV(X));
1413 }
1414 break;
1415
Reid Spencer3da59db2006-11-27 01:05:10 +00001416 case Instruction::Trunc:
Chris Lattnerb2f3e702007-01-15 01:58:56 +00001417 return SCEVTruncateExpr::get(getSCEV(I->getOperand(0)), I->getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00001418
1419 case Instruction::ZExt:
Chris Lattnerb2f3e702007-01-15 01:58:56 +00001420 return SCEVZeroExtendExpr::get(getSCEV(I->getOperand(0)), I->getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00001421
1422 case Instruction::BitCast:
1423 // BitCasts are no-op casts so we just eliminate the cast.
Chris Lattner42a75512007-01-15 02:27:26 +00001424 if (I->getType()->isInteger() &&
1425 I->getOperand(0)->getType()->isInteger())
Chris Lattner82e8a8f2006-12-11 00:12:31 +00001426 return getSCEV(I->getOperand(0));
1427 break;
Chris Lattner53e677a2004-04-02 20:23:17 +00001428
1429 case Instruction::PHI:
1430 return createNodeForPHI(cast<PHINode>(I));
1431
1432 default: // We cannot analyze this expression.
1433 break;
1434 }
1435 }
1436
1437 return SCEVUnknown::get(V);
1438}
1439
1440
1441
1442//===----------------------------------------------------------------------===//
1443// Iteration Count Computation Code
1444//
1445
1446/// getIterationCount - If the specified loop has a predictable iteration
1447/// count, return it. Note that it is not valid to call this method on a
1448/// loop without a loop-invariant iteration count.
1449SCEVHandle ScalarEvolutionsImpl::getIterationCount(const Loop *L) {
1450 std::map<const Loop*, SCEVHandle>::iterator I = IterationCounts.find(L);
1451 if (I == IterationCounts.end()) {
1452 SCEVHandle ItCount = ComputeIterationCount(L);
1453 I = IterationCounts.insert(std::make_pair(L, ItCount)).first;
1454 if (ItCount != UnknownValue) {
1455 assert(ItCount->isLoopInvariant(L) &&
1456 "Computed trip count isn't loop invariant for loop!");
1457 ++NumTripCountsComputed;
1458 } else if (isa<PHINode>(L->getHeader()->begin())) {
1459 // Only count loops that have phi nodes as not being computable.
1460 ++NumTripCountsNotComputed;
1461 }
1462 }
1463 return I->second;
1464}
1465
1466/// ComputeIterationCount - Compute the number of times the specified loop
1467/// will iterate.
1468SCEVHandle ScalarEvolutionsImpl::ComputeIterationCount(const Loop *L) {
1469 // If the loop has a non-one exit block count, we can't analyze it.
Chris Lattnerf1ab4b42004-04-18 22:14:10 +00001470 std::vector<BasicBlock*> ExitBlocks;
1471 L->getExitBlocks(ExitBlocks);
1472 if (ExitBlocks.size() != 1) return UnknownValue;
Chris Lattner53e677a2004-04-02 20:23:17 +00001473
1474 // Okay, there is one exit block. Try to find the condition that causes the
1475 // loop to be exited.
Chris Lattnerf1ab4b42004-04-18 22:14:10 +00001476 BasicBlock *ExitBlock = ExitBlocks[0];
Chris Lattner53e677a2004-04-02 20:23:17 +00001477
1478 BasicBlock *ExitingBlock = 0;
1479 for (pred_iterator PI = pred_begin(ExitBlock), E = pred_end(ExitBlock);
1480 PI != E; ++PI)
1481 if (L->contains(*PI)) {
1482 if (ExitingBlock == 0)
1483 ExitingBlock = *PI;
1484 else
1485 return UnknownValue; // More than one block exiting!
1486 }
1487 assert(ExitingBlock && "No exits from loop, something is broken!");
1488
1489 // Okay, we've computed the exiting block. See what condition causes us to
1490 // exit.
1491 //
1492 // FIXME: we should be able to handle switch instructions (with a single exit)
Chris Lattner53e677a2004-04-02 20:23:17 +00001493 BranchInst *ExitBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
1494 if (ExitBr == 0) return UnknownValue;
1495 assert(ExitBr->isConditional() && "If unconditional, it can't be in loop!");
Chris Lattner8b0e3602007-01-07 02:24:26 +00001496
1497 // At this point, we know we have a conditional branch that determines whether
1498 // the loop is exited. However, we don't know if the branch is executed each
1499 // time through the loop. If not, then the execution count of the branch will
1500 // not be equal to the trip count of the loop.
1501 //
1502 // Currently we check for this by checking to see if the Exit branch goes to
1503 // the loop header. If so, we know it will always execute the same number of
Chris Lattner192e4032007-01-14 01:24:47 +00001504 // times as the loop. We also handle the case where the exit block *is* the
1505 // loop header. This is common for un-rotated loops. More extensive analysis
1506 // could be done to handle more cases here.
Chris Lattner8b0e3602007-01-07 02:24:26 +00001507 if (ExitBr->getSuccessor(0) != L->getHeader() &&
Chris Lattner192e4032007-01-14 01:24:47 +00001508 ExitBr->getSuccessor(1) != L->getHeader() &&
1509 ExitBr->getParent() != L->getHeader())
Chris Lattner8b0e3602007-01-07 02:24:26 +00001510 return UnknownValue;
1511
Reid Spencere4d87aa2006-12-23 06:05:41 +00001512 ICmpInst *ExitCond = dyn_cast<ICmpInst>(ExitBr->getCondition());
1513
1514 // If its not an integer comparison then compute it the hard way.
1515 // Note that ICmpInst deals with pointer comparisons too so we must check
1516 // the type of the operand.
Chris Lattner8b0e3602007-01-07 02:24:26 +00001517 if (ExitCond == 0 || isa<PointerType>(ExitCond->getOperand(0)->getType()))
Chris Lattner7980fb92004-04-17 18:36:24 +00001518 return ComputeIterationCountExhaustively(L, ExitBr->getCondition(),
1519 ExitBr->getSuccessor(0) == ExitBlock);
Chris Lattner53e677a2004-04-02 20:23:17 +00001520
Reid Spencere4d87aa2006-12-23 06:05:41 +00001521 // If the condition was exit on true, convert the condition to exit on false
1522 ICmpInst::Predicate Cond;
Chris Lattner673e02b2004-10-12 01:49:27 +00001523 if (ExitBr->getSuccessor(1) == ExitBlock)
Reid Spencere4d87aa2006-12-23 06:05:41 +00001524 Cond = ExitCond->getPredicate();
Chris Lattner673e02b2004-10-12 01:49:27 +00001525 else
Reid Spencere4d87aa2006-12-23 06:05:41 +00001526 Cond = ExitCond->getInversePredicate();
Chris Lattner673e02b2004-10-12 01:49:27 +00001527
1528 // Handle common loops like: for (X = "string"; *X; ++X)
1529 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
1530 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
1531 SCEVHandle ItCnt =
1532 ComputeLoadConstantCompareIterationCount(LI, RHS, L, Cond);
1533 if (!isa<SCEVCouldNotCompute>(ItCnt)) return ItCnt;
1534 }
1535
Chris Lattner53e677a2004-04-02 20:23:17 +00001536 SCEVHandle LHS = getSCEV(ExitCond->getOperand(0));
1537 SCEVHandle RHS = getSCEV(ExitCond->getOperand(1));
1538
1539 // Try to evaluate any dependencies out of the loop.
1540 SCEVHandle Tmp = getSCEVAtScope(LHS, L);
1541 if (!isa<SCEVCouldNotCompute>(Tmp)) LHS = Tmp;
1542 Tmp = getSCEVAtScope(RHS, L);
1543 if (!isa<SCEVCouldNotCompute>(Tmp)) RHS = Tmp;
1544
Reid Spencere4d87aa2006-12-23 06:05:41 +00001545 // At this point, we would like to compute how many iterations of the
1546 // loop the predicate will return true for these inputs.
Chris Lattner53e677a2004-04-02 20:23:17 +00001547 if (isa<SCEVConstant>(LHS) && !isa<SCEVConstant>(RHS)) {
1548 // If there is a constant, force it into the RHS.
1549 std::swap(LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00001550 Cond = ICmpInst::getSwappedPredicate(Cond);
Chris Lattner53e677a2004-04-02 20:23:17 +00001551 }
1552
1553 // FIXME: think about handling pointer comparisons! i.e.:
1554 // while (P != P+100) ++P;
1555
1556 // If we have a comparison of a chrec against a constant, try to use value
1557 // ranges to answer this query.
1558 if (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
1559 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
1560 if (AddRec->getLoop() == L) {
1561 // Form the comparison range using the constant of the correct type so
1562 // that the ConstantRange class knows to do a signed or unsigned
1563 // comparison.
1564 ConstantInt *CompVal = RHSC->getValue();
1565 const Type *RealTy = ExitCond->getOperand(0)->getType();
Reid Spencer4da49122006-12-12 05:05:00 +00001566 CompVal = dyn_cast<ConstantInt>(
Reid Spencerb6ba3e62006-12-12 09:17:50 +00001567 ConstantExpr::getBitCast(CompVal, RealTy));
Chris Lattner53e677a2004-04-02 20:23:17 +00001568 if (CompVal) {
1569 // Form the constant range.
1570 ConstantRange CompRange(Cond, CompVal);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001571
Reid Spencere4d87aa2006-12-23 06:05:41 +00001572 SCEVHandle Ret = AddRec->getNumIterationsInRange(CompRange,
Reid Spencerc5b206b2006-12-31 05:48:39 +00001573 false /*Always treat as unsigned range*/);
Chris Lattner53e677a2004-04-02 20:23:17 +00001574 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
1575 }
1576 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001577
Chris Lattner53e677a2004-04-02 20:23:17 +00001578 switch (Cond) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00001579 case ICmpInst::ICMP_NE: { // while (X != Y)
Chris Lattner53e677a2004-04-02 20:23:17 +00001580 // Convert to: while (X-Y != 0)
Reid Spencere4d87aa2006-12-23 06:05:41 +00001581 SCEVHandle TC = HowFarToZero(SCEV::getMinusSCEV(LHS, RHS), L);
1582 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
Chris Lattner53e677a2004-04-02 20:23:17 +00001583 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00001584 }
1585 case ICmpInst::ICMP_EQ: {
Chris Lattner53e677a2004-04-02 20:23:17 +00001586 // Convert to: while (X-Y == 0) // while (X == Y)
Reid Spencere4d87aa2006-12-23 06:05:41 +00001587 SCEVHandle TC = HowFarToNonZero(SCEV::getMinusSCEV(LHS, RHS), L);
1588 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
Chris Lattner53e677a2004-04-02 20:23:17 +00001589 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00001590 }
1591 case ICmpInst::ICMP_SLT: {
1592 SCEVHandle TC = HowManyLessThans(LHS, RHS, L);
1593 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
Chris Lattnerdb25de42005-08-15 23:33:51 +00001594 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00001595 }
1596 case ICmpInst::ICMP_SGT: {
1597 SCEVHandle TC = HowManyLessThans(RHS, LHS, L);
1598 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
Chris Lattnerdb25de42005-08-15 23:33:51 +00001599 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00001600 }
Chris Lattner53e677a2004-04-02 20:23:17 +00001601 default:
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00001602#if 0
Bill Wendlinge8156192006-12-07 01:30:32 +00001603 cerr << "ComputeIterationCount ";
Chris Lattner53e677a2004-04-02 20:23:17 +00001604 if (ExitCond->getOperand(0)->getType()->isUnsigned())
Bill Wendlinge8156192006-12-07 01:30:32 +00001605 cerr << "[unsigned] ";
1606 cerr << *LHS << " "
Reid Spencere4d87aa2006-12-23 06:05:41 +00001607 << Instruction::getOpcodeName(Instruction::ICmp)
1608 << " " << *RHS << "\n";
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00001609#endif
Chris Lattnere34c0b42004-04-03 00:43:03 +00001610 break;
Chris Lattner53e677a2004-04-02 20:23:17 +00001611 }
Chris Lattner7980fb92004-04-17 18:36:24 +00001612 return ComputeIterationCountExhaustively(L, ExitCond,
Reid Spencere4d87aa2006-12-23 06:05:41 +00001613 ExitBr->getSuccessor(0) == ExitBlock);
Chris Lattner7980fb92004-04-17 18:36:24 +00001614}
1615
Chris Lattner673e02b2004-10-12 01:49:27 +00001616static ConstantInt *
1617EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, Constant *C) {
1618 SCEVHandle InVal = SCEVConstant::get(cast<ConstantInt>(C));
1619 SCEVHandle Val = AddRec->evaluateAtIteration(InVal);
1620 assert(isa<SCEVConstant>(Val) &&
1621 "Evaluation of SCEV at constant didn't fold correctly?");
1622 return cast<SCEVConstant>(Val)->getValue();
1623}
1624
1625/// GetAddressedElementFromGlobal - Given a global variable with an initializer
1626/// and a GEP expression (missing the pointer index) indexing into it, return
1627/// the addressed element of the initializer or null if the index expression is
1628/// invalid.
1629static Constant *
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001630GetAddressedElementFromGlobal(GlobalVariable *GV,
Chris Lattner673e02b2004-10-12 01:49:27 +00001631 const std::vector<ConstantInt*> &Indices) {
1632 Constant *Init = GV->getInitializer();
1633 for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
Reid Spencerb83eb642006-10-20 07:07:24 +00001634 uint64_t Idx = Indices[i]->getZExtValue();
Chris Lattner673e02b2004-10-12 01:49:27 +00001635 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
1636 assert(Idx < CS->getNumOperands() && "Bad struct index!");
1637 Init = cast<Constant>(CS->getOperand(Idx));
1638 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
1639 if (Idx >= CA->getNumOperands()) return 0; // Bogus program
1640 Init = cast<Constant>(CA->getOperand(Idx));
1641 } else if (isa<ConstantAggregateZero>(Init)) {
1642 if (const StructType *STy = dyn_cast<StructType>(Init->getType())) {
1643 assert(Idx < STy->getNumElements() && "Bad struct index!");
1644 Init = Constant::getNullValue(STy->getElementType(Idx));
1645 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Init->getType())) {
1646 if (Idx >= ATy->getNumElements()) return 0; // Bogus program
1647 Init = Constant::getNullValue(ATy->getElementType());
1648 } else {
1649 assert(0 && "Unknown constant aggregate type!");
1650 }
1651 return 0;
1652 } else {
1653 return 0; // Unknown initializer type
1654 }
1655 }
1656 return Init;
1657}
1658
1659/// ComputeLoadConstantCompareIterationCount - Given an exit condition of
1660/// 'setcc load X, cst', try to se if we can compute the trip count.
1661SCEVHandle ScalarEvolutionsImpl::
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001662ComputeLoadConstantCompareIterationCount(LoadInst *LI, Constant *RHS,
Reid Spencere4d87aa2006-12-23 06:05:41 +00001663 const Loop *L,
1664 ICmpInst::Predicate predicate) {
Chris Lattner673e02b2004-10-12 01:49:27 +00001665 if (LI->isVolatile()) return UnknownValue;
1666
1667 // Check to see if the loaded pointer is a getelementptr of a global.
1668 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
1669 if (!GEP) return UnknownValue;
1670
1671 // Make sure that it is really a constant global we are gepping, with an
1672 // initializer, and make sure the first IDX is really 0.
1673 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
1674 if (!GV || !GV->isConstant() || !GV->hasInitializer() ||
1675 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
1676 !cast<Constant>(GEP->getOperand(1))->isNullValue())
1677 return UnknownValue;
1678
1679 // Okay, we allow one non-constant index into the GEP instruction.
1680 Value *VarIdx = 0;
1681 std::vector<ConstantInt*> Indexes;
1682 unsigned VarIdxNum = 0;
1683 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
1684 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
1685 Indexes.push_back(CI);
1686 } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
1687 if (VarIdx) return UnknownValue; // Multiple non-constant idx's.
1688 VarIdx = GEP->getOperand(i);
1689 VarIdxNum = i-2;
1690 Indexes.push_back(0);
1691 }
1692
1693 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
1694 // Check to see if X is a loop variant variable value now.
1695 SCEVHandle Idx = getSCEV(VarIdx);
1696 SCEVHandle Tmp = getSCEVAtScope(Idx, L);
1697 if (!isa<SCEVCouldNotCompute>(Tmp)) Idx = Tmp;
1698
1699 // We can only recognize very limited forms of loop index expressions, in
1700 // particular, only affine AddRec's like {C1,+,C2}.
1701 SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
1702 if (!IdxExpr || !IdxExpr->isAffine() || IdxExpr->isLoopInvariant(L) ||
1703 !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
1704 !isa<SCEVConstant>(IdxExpr->getOperand(1)))
1705 return UnknownValue;
1706
1707 unsigned MaxSteps = MaxBruteForceIterations;
1708 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
Reid Spencerb83eb642006-10-20 07:07:24 +00001709 ConstantInt *ItCst =
Reid Spencerc5b206b2006-12-31 05:48:39 +00001710 ConstantInt::get(IdxExpr->getType(), IterationNum);
Chris Lattner673e02b2004-10-12 01:49:27 +00001711 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst);
1712
1713 // Form the GEP offset.
1714 Indexes[VarIdxNum] = Val;
1715
1716 Constant *Result = GetAddressedElementFromGlobal(GV, Indexes);
1717 if (Result == 0) break; // Cannot compute!
1718
1719 // Evaluate the condition for this iteration.
Reid Spencere4d87aa2006-12-23 06:05:41 +00001720 Result = ConstantExpr::getICmp(predicate, Result, RHS);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001721 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure
Reid Spencer579dca12007-01-12 04:24:46 +00001722 if (cast<ConstantInt>(Result)->getZExtValue() == false) {
Chris Lattner673e02b2004-10-12 01:49:27 +00001723#if 0
Bill Wendlinge8156192006-12-07 01:30:32 +00001724 cerr << "\n***\n*** Computed loop count " << *ItCst
1725 << "\n*** From global " << *GV << "*** BB: " << *L->getHeader()
1726 << "***\n";
Chris Lattner673e02b2004-10-12 01:49:27 +00001727#endif
1728 ++NumArrayLenItCounts;
1729 return SCEVConstant::get(ItCst); // Found terminating iteration!
1730 }
1731 }
1732 return UnknownValue;
1733}
1734
1735
Chris Lattner3221ad02004-04-17 22:58:41 +00001736/// CanConstantFold - Return true if we can constant fold an instruction of the
1737/// specified type, assuming that all operands were constants.
1738static bool CanConstantFold(const Instruction *I) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00001739 if (isa<BinaryOperator>(I) || isa<ShiftInst>(I) || isa<CmpInst>(I) ||
Chris Lattner3221ad02004-04-17 22:58:41 +00001740 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I))
1741 return true;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001742
Chris Lattner3221ad02004-04-17 22:58:41 +00001743 if (const CallInst *CI = dyn_cast<CallInst>(I))
1744 if (const Function *F = CI->getCalledFunction())
1745 return canConstantFoldCallTo((Function*)F); // FIXME: elim cast
1746 return false;
Chris Lattner7980fb92004-04-17 18:36:24 +00001747}
1748
Chris Lattner3221ad02004-04-17 22:58:41 +00001749/// ConstantFold - Constant fold an instruction of the specified type with the
1750/// specified constant operands. This function may modify the operands vector.
1751static Constant *ConstantFold(const Instruction *I,
1752 std::vector<Constant*> &Operands) {
Chris Lattner7980fb92004-04-17 18:36:24 +00001753 if (isa<BinaryOperator>(I) || isa<ShiftInst>(I))
1754 return ConstantExpr::get(I->getOpcode(), Operands[0], Operands[1]);
1755
Reid Spencer3da59db2006-11-27 01:05:10 +00001756 if (isa<CastInst>(I))
1757 return ConstantExpr::getCast(I->getOpcode(), Operands[0], I->getType());
1758
Chris Lattner7980fb92004-04-17 18:36:24 +00001759 switch (I->getOpcode()) {
Chris Lattner7980fb92004-04-17 18:36:24 +00001760 case Instruction::Select:
1761 return ConstantExpr::getSelect(Operands[0], Operands[1], Operands[2]);
1762 case Instruction::Call:
Reid Spencere8404342004-07-18 00:18:30 +00001763 if (Function *GV = dyn_cast<Function>(Operands[0])) {
Chris Lattner7980fb92004-04-17 18:36:24 +00001764 Operands.erase(Operands.begin());
Reid Spencere8404342004-07-18 00:18:30 +00001765 return ConstantFoldCall(cast<Function>(GV), Operands);
Chris Lattner7980fb92004-04-17 18:36:24 +00001766 }
Chris Lattner7980fb92004-04-17 18:36:24 +00001767 return 0;
Reid Spencere4d87aa2006-12-23 06:05:41 +00001768 case Instruction::GetElementPtr: {
Chris Lattner7980fb92004-04-17 18:36:24 +00001769 Constant *Base = Operands[0];
1770 Operands.erase(Operands.begin());
1771 return ConstantExpr::getGetElementPtr(Base, Operands);
1772 }
Reid Spencere4d87aa2006-12-23 06:05:41 +00001773 case Instruction::ICmp:
1774 return ConstantExpr::getICmp(
1775 cast<ICmpInst>(I)->getPredicate(), Operands[0], Operands[1]);
1776 case Instruction::FCmp:
1777 return ConstantExpr::getFCmp(
1778 cast<FCmpInst>(I)->getPredicate(), Operands[0], Operands[1]);
1779 }
Chris Lattner7980fb92004-04-17 18:36:24 +00001780 return 0;
1781}
1782
1783
Chris Lattner3221ad02004-04-17 22:58:41 +00001784/// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
1785/// in the loop that V is derived from. We allow arbitrary operations along the
1786/// way, but the operands of an operation must either be constants or a value
1787/// derived from a constant PHI. If this expression does not fit with these
1788/// constraints, return null.
1789static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
1790 // If this is not an instruction, or if this is an instruction outside of the
1791 // loop, it can't be derived from a loop PHI.
1792 Instruction *I = dyn_cast<Instruction>(V);
1793 if (I == 0 || !L->contains(I->getParent())) return 0;
1794
1795 if (PHINode *PN = dyn_cast<PHINode>(I))
1796 if (L->getHeader() == I->getParent())
1797 return PN;
1798 else
1799 // We don't currently keep track of the control flow needed to evaluate
1800 // PHIs, so we cannot handle PHIs inside of loops.
1801 return 0;
1802
1803 // If we won't be able to constant fold this expression even if the operands
1804 // are constants, return early.
1805 if (!CanConstantFold(I)) return 0;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001806
Chris Lattner3221ad02004-04-17 22:58:41 +00001807 // Otherwise, we can evaluate this instruction if all of its operands are
1808 // constant or derived from a PHI node themselves.
1809 PHINode *PHI = 0;
1810 for (unsigned Op = 0, e = I->getNumOperands(); Op != e; ++Op)
1811 if (!(isa<Constant>(I->getOperand(Op)) ||
1812 isa<GlobalValue>(I->getOperand(Op)))) {
1813 PHINode *P = getConstantEvolvingPHI(I->getOperand(Op), L);
1814 if (P == 0) return 0; // Not evolving from PHI
1815 if (PHI == 0)
1816 PHI = P;
1817 else if (PHI != P)
1818 return 0; // Evolving from multiple different PHIs.
1819 }
1820
1821 // This is a expression evolving from a constant PHI!
1822 return PHI;
1823}
1824
1825/// EvaluateExpression - Given an expression that passes the
1826/// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
1827/// in the loop has the value PHIVal. If we can't fold this expression for some
1828/// reason, return null.
1829static Constant *EvaluateExpression(Value *V, Constant *PHIVal) {
1830 if (isa<PHINode>(V)) return PHIVal;
Chris Lattner3221ad02004-04-17 22:58:41 +00001831 if (GlobalValue *GV = dyn_cast<GlobalValue>(V))
Reid Spencere8404342004-07-18 00:18:30 +00001832 return GV;
1833 if (Constant *C = dyn_cast<Constant>(V)) return C;
Chris Lattner3221ad02004-04-17 22:58:41 +00001834 Instruction *I = cast<Instruction>(V);
1835
1836 std::vector<Constant*> Operands;
1837 Operands.resize(I->getNumOperands());
1838
1839 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
1840 Operands[i] = EvaluateExpression(I->getOperand(i), PHIVal);
1841 if (Operands[i] == 0) return 0;
1842 }
1843
1844 return ConstantFold(I, Operands);
1845}
1846
1847/// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
1848/// in the header of its containing loop, we know the loop executes a
1849/// constant number of times, and the PHI node is just a recurrence
1850/// involving constants, fold it.
1851Constant *ScalarEvolutionsImpl::
1852getConstantEvolutionLoopExitValue(PHINode *PN, uint64_t Its, const Loop *L) {
1853 std::map<PHINode*, Constant*>::iterator I =
1854 ConstantEvolutionLoopExitValue.find(PN);
1855 if (I != ConstantEvolutionLoopExitValue.end())
1856 return I->second;
1857
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001858 if (Its > MaxBruteForceIterations)
Chris Lattner3221ad02004-04-17 22:58:41 +00001859 return ConstantEvolutionLoopExitValue[PN] = 0; // Not going to evaluate it.
1860
1861 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
1862
1863 // Since the loop is canonicalized, the PHI node must have two entries. One
1864 // entry must be a constant (coming in from outside of the loop), and the
1865 // second must be derived from the same PHI.
1866 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
1867 Constant *StartCST =
1868 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
1869 if (StartCST == 0)
1870 return RetVal = 0; // Must be a constant.
1871
1872 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
1873 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
1874 if (PN2 != PN)
1875 return RetVal = 0; // Not derived from same PHI.
1876
1877 // Execute the loop symbolically to determine the exit value.
1878 unsigned IterationNum = 0;
1879 unsigned NumIterations = Its;
1880 if (NumIterations != Its)
1881 return RetVal = 0; // More than 2^32 iterations??
1882
1883 for (Constant *PHIVal = StartCST; ; ++IterationNum) {
1884 if (IterationNum == NumIterations)
1885 return RetVal = PHIVal; // Got exit value!
1886
1887 // Compute the value of the PHI node for the next iteration.
1888 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
1889 if (NextPHI == PHIVal)
1890 return RetVal = NextPHI; // Stopped evolving!
1891 if (NextPHI == 0)
1892 return 0; // Couldn't evaluate!
1893 PHIVal = NextPHI;
1894 }
1895}
1896
Chris Lattner7980fb92004-04-17 18:36:24 +00001897/// ComputeIterationCountExhaustively - If the trip is known to execute a
1898/// constant number of times (the condition evolves only from constants),
1899/// try to evaluate a few iterations of the loop until we get the exit
1900/// condition gets a value of ExitWhen (true or false). If we cannot
1901/// evaluate the trip count of the loop, return UnknownValue.
1902SCEVHandle ScalarEvolutionsImpl::
1903ComputeIterationCountExhaustively(const Loop *L, Value *Cond, bool ExitWhen) {
1904 PHINode *PN = getConstantEvolvingPHI(Cond, L);
1905 if (PN == 0) return UnknownValue;
1906
1907 // Since the loop is canonicalized, the PHI node must have two entries. One
1908 // entry must be a constant (coming in from outside of the loop), and the
1909 // second must be derived from the same PHI.
1910 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
1911 Constant *StartCST =
1912 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
1913 if (StartCST == 0) return UnknownValue; // Must be a constant.
1914
1915 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
1916 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
1917 if (PN2 != PN) return UnknownValue; // Not derived from same PHI.
1918
1919 // Okay, we find a PHI node that defines the trip count of this loop. Execute
1920 // the loop symbolically to determine when the condition gets a value of
1921 // "ExitWhen".
1922 unsigned IterationNum = 0;
1923 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis.
1924 for (Constant *PHIVal = StartCST;
1925 IterationNum != MaxIterations; ++IterationNum) {
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001926 ConstantInt *CondVal =
1927 dyn_cast_or_null<ConstantInt>(EvaluateExpression(Cond, PHIVal));
Chris Lattner3221ad02004-04-17 22:58:41 +00001928
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001929 // Couldn't symbolically evaluate.
Chris Lattneref3baf02007-01-12 18:28:58 +00001930 if (!CondVal) return UnknownValue;
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001931
Jeff Cohen1b307542007-01-15 20:27:18 +00001932 if (CondVal->getZExtValue() == uint64_t(ExitWhen)) {
Chris Lattner3221ad02004-04-17 22:58:41 +00001933 ConstantEvolutionLoopExitValue[PN] = PHIVal;
Chris Lattner7980fb92004-04-17 18:36:24 +00001934 ++NumBruteForceTripCountsComputed;
Reid Spencerc5b206b2006-12-31 05:48:39 +00001935 return SCEVConstant::get(ConstantInt::get(Type::Int32Ty, IterationNum));
Chris Lattner7980fb92004-04-17 18:36:24 +00001936 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001937
Chris Lattner3221ad02004-04-17 22:58:41 +00001938 // Compute the value of the PHI node for the next iteration.
1939 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
1940 if (NextPHI == 0 || NextPHI == PHIVal)
Chris Lattner7980fb92004-04-17 18:36:24 +00001941 return UnknownValue; // Couldn't evaluate or not making progress...
Chris Lattner3221ad02004-04-17 22:58:41 +00001942 PHIVal = NextPHI;
Chris Lattner7980fb92004-04-17 18:36:24 +00001943 }
1944
1945 // Too many iterations were needed to evaluate.
Chris Lattner53e677a2004-04-02 20:23:17 +00001946 return UnknownValue;
1947}
1948
1949/// getSCEVAtScope - Compute the value of the specified expression within the
1950/// indicated loop (which may be null to indicate in no loop). If the
1951/// expression cannot be evaluated, return UnknownValue.
1952SCEVHandle ScalarEvolutionsImpl::getSCEVAtScope(SCEV *V, const Loop *L) {
1953 // FIXME: this should be turned into a virtual method on SCEV!
1954
Chris Lattner3221ad02004-04-17 22:58:41 +00001955 if (isa<SCEVConstant>(V)) return V;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001956
Chris Lattner3221ad02004-04-17 22:58:41 +00001957 // If this instruction is evolves from a constant-evolving PHI, compute the
1958 // exit value from the loop without using SCEVs.
1959 if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
1960 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
1961 const Loop *LI = this->LI[I->getParent()];
1962 if (LI && LI->getParentLoop() == L) // Looking for loop exit value.
1963 if (PHINode *PN = dyn_cast<PHINode>(I))
1964 if (PN->getParent() == LI->getHeader()) {
1965 // Okay, there is no closed form solution for the PHI node. Check
1966 // to see if the loop that contains it has a known iteration count.
1967 // If so, we may be able to force computation of the exit value.
1968 SCEVHandle IterationCount = getIterationCount(LI);
1969 if (SCEVConstant *ICC = dyn_cast<SCEVConstant>(IterationCount)) {
1970 // Okay, we know how many times the containing loop executes. If
1971 // this is a constant evolving PHI node, get the final value at
1972 // the specified iteration number.
1973 Constant *RV = getConstantEvolutionLoopExitValue(PN,
Reid Spencerb83eb642006-10-20 07:07:24 +00001974 ICC->getValue()->getZExtValue(),
Chris Lattner3221ad02004-04-17 22:58:41 +00001975 LI);
1976 if (RV) return SCEVUnknown::get(RV);
1977 }
1978 }
1979
Reid Spencer09906f32006-12-04 21:33:23 +00001980 // Okay, this is an expression that we cannot symbolically evaluate
Chris Lattner3221ad02004-04-17 22:58:41 +00001981 // into a SCEV. Check to see if it's possible to symbolically evaluate
Reid Spencer09906f32006-12-04 21:33:23 +00001982 // the arguments into constants, and if so, try to constant propagate the
Chris Lattner3221ad02004-04-17 22:58:41 +00001983 // result. This is particularly useful for computing loop exit values.
1984 if (CanConstantFold(I)) {
1985 std::vector<Constant*> Operands;
1986 Operands.reserve(I->getNumOperands());
1987 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
1988 Value *Op = I->getOperand(i);
1989 if (Constant *C = dyn_cast<Constant>(Op)) {
1990 Operands.push_back(C);
Chris Lattner3221ad02004-04-17 22:58:41 +00001991 } else {
1992 SCEVHandle OpV = getSCEVAtScope(getSCEV(Op), L);
1993 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(OpV))
Reid Spencerd977d862006-12-12 23:36:14 +00001994 Operands.push_back(ConstantExpr::getIntegerCast(SC->getValue(),
1995 Op->getType(),
1996 false));
Chris Lattner3221ad02004-04-17 22:58:41 +00001997 else if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(OpV)) {
1998 if (Constant *C = dyn_cast<Constant>(SU->getValue()))
Reid Spencerd977d862006-12-12 23:36:14 +00001999 Operands.push_back(ConstantExpr::getIntegerCast(C,
2000 Op->getType(),
2001 false));
Chris Lattner3221ad02004-04-17 22:58:41 +00002002 else
2003 return V;
2004 } else {
2005 return V;
2006 }
2007 }
2008 }
2009 return SCEVUnknown::get(ConstantFold(I, Operands));
2010 }
2011 }
2012
2013 // This is some other type of SCEVUnknown, just return it.
2014 return V;
2015 }
2016
Chris Lattner53e677a2004-04-02 20:23:17 +00002017 if (SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
2018 // Avoid performing the look-up in the common case where the specified
2019 // expression has no loop-variant portions.
2020 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
2021 SCEVHandle OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
2022 if (OpAtScope != Comm->getOperand(i)) {
2023 if (OpAtScope == UnknownValue) return UnknownValue;
2024 // Okay, at least one of these operands is loop variant but might be
2025 // foldable. Build a new instance of the folded commutative expression.
Chris Lattner3221ad02004-04-17 22:58:41 +00002026 std::vector<SCEVHandle> NewOps(Comm->op_begin(), Comm->op_begin()+i);
Chris Lattner53e677a2004-04-02 20:23:17 +00002027 NewOps.push_back(OpAtScope);
2028
2029 for (++i; i != e; ++i) {
2030 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
2031 if (OpAtScope == UnknownValue) return UnknownValue;
2032 NewOps.push_back(OpAtScope);
2033 }
2034 if (isa<SCEVAddExpr>(Comm))
2035 return SCEVAddExpr::get(NewOps);
2036 assert(isa<SCEVMulExpr>(Comm) && "Only know about add and mul!");
2037 return SCEVMulExpr::get(NewOps);
2038 }
2039 }
2040 // If we got here, all operands are loop invariant.
2041 return Comm;
2042 }
2043
Chris Lattner60a05cc2006-04-01 04:48:52 +00002044 if (SCEVSDivExpr *Div = dyn_cast<SCEVSDivExpr>(V)) {
2045 SCEVHandle LHS = getSCEVAtScope(Div->getLHS(), L);
Chris Lattner53e677a2004-04-02 20:23:17 +00002046 if (LHS == UnknownValue) return LHS;
Chris Lattner60a05cc2006-04-01 04:48:52 +00002047 SCEVHandle RHS = getSCEVAtScope(Div->getRHS(), L);
Chris Lattner53e677a2004-04-02 20:23:17 +00002048 if (RHS == UnknownValue) return RHS;
Chris Lattner60a05cc2006-04-01 04:48:52 +00002049 if (LHS == Div->getLHS() && RHS == Div->getRHS())
2050 return Div; // must be loop invariant
2051 return SCEVSDivExpr::get(LHS, RHS);
Chris Lattner53e677a2004-04-02 20:23:17 +00002052 }
2053
2054 // If this is a loop recurrence for a loop that does not contain L, then we
2055 // are dealing with the final value computed by the loop.
2056 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
2057 if (!L || !AddRec->getLoop()->contains(L->getHeader())) {
2058 // To evaluate this recurrence, we need to know how many times the AddRec
2059 // loop iterates. Compute this now.
2060 SCEVHandle IterationCount = getIterationCount(AddRec->getLoop());
2061 if (IterationCount == UnknownValue) return UnknownValue;
2062 IterationCount = getTruncateOrZeroExtend(IterationCount,
2063 AddRec->getType());
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002064
Chris Lattner53e677a2004-04-02 20:23:17 +00002065 // If the value is affine, simplify the expression evaluation to just
2066 // Start + Step*IterationCount.
2067 if (AddRec->isAffine())
2068 return SCEVAddExpr::get(AddRec->getStart(),
2069 SCEVMulExpr::get(IterationCount,
2070 AddRec->getOperand(1)));
2071
2072 // Otherwise, evaluate it the hard way.
2073 return AddRec->evaluateAtIteration(IterationCount);
2074 }
2075 return UnknownValue;
2076 }
2077
2078 //assert(0 && "Unknown SCEV type!");
2079 return UnknownValue;
2080}
2081
2082
2083/// SolveQuadraticEquation - Find the roots of the quadratic equation for the
2084/// given quadratic chrec {L,+,M,+,N}. This returns either the two roots (which
2085/// might be the same) or two SCEVCouldNotCompute objects.
2086///
2087static std::pair<SCEVHandle,SCEVHandle>
2088SolveQuadraticEquation(const SCEVAddRecExpr *AddRec) {
2089 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
2090 SCEVConstant *L = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
2091 SCEVConstant *M = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
2092 SCEVConstant *N = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002093
Chris Lattner53e677a2004-04-02 20:23:17 +00002094 // We currently can only solve this if the coefficients are constants.
2095 if (!L || !M || !N) {
2096 SCEV *CNC = new SCEVCouldNotCompute();
2097 return std::make_pair(CNC, CNC);
2098 }
2099
Reid Spencer1628cec2006-10-26 06:15:43 +00002100 Constant *C = L->getValue();
2101 Constant *Two = ConstantInt::get(C->getType(), 2);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002102
Chris Lattner53e677a2004-04-02 20:23:17 +00002103 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
Chris Lattner53e677a2004-04-02 20:23:17 +00002104 // The B coefficient is M-N/2
2105 Constant *B = ConstantExpr::getSub(M->getValue(),
Reid Spencer1628cec2006-10-26 06:15:43 +00002106 ConstantExpr::getSDiv(N->getValue(),
Chris Lattner53e677a2004-04-02 20:23:17 +00002107 Two));
2108 // The A coefficient is N/2
Reid Spencer1628cec2006-10-26 06:15:43 +00002109 Constant *A = ConstantExpr::getSDiv(N->getValue(), Two);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002110
Chris Lattner53e677a2004-04-02 20:23:17 +00002111 // Compute the B^2-4ac term.
2112 Constant *SqrtTerm =
2113 ConstantExpr::getMul(ConstantInt::get(C->getType(), 4),
2114 ConstantExpr::getMul(A, C));
2115 SqrtTerm = ConstantExpr::getSub(ConstantExpr::getMul(B, B), SqrtTerm);
2116
2117 // Compute floor(sqrt(B^2-4ac))
Reid Spencerc5b206b2006-12-31 05:48:39 +00002118 uint64_t SqrtValV = cast<ConstantInt>(SqrtTerm)->getZExtValue();
Chris Lattner219c1412004-10-25 18:40:08 +00002119 uint64_t SqrtValV2 = (uint64_t)sqrt((double)SqrtValV);
Chris Lattner53e677a2004-04-02 20:23:17 +00002120 // The square root might not be precise for arbitrary 64-bit integer
2121 // values. Do some sanity checks to ensure it's correct.
2122 if (SqrtValV2*SqrtValV2 > SqrtValV ||
2123 (SqrtValV2+1)*(SqrtValV2+1) <= SqrtValV) {
2124 SCEV *CNC = new SCEVCouldNotCompute();
2125 return std::make_pair(CNC, CNC);
2126 }
2127
Reid Spencerc5b206b2006-12-31 05:48:39 +00002128 ConstantInt *SqrtVal = ConstantInt::get(Type::Int64Ty, SqrtValV2);
Reid Spencerd977d862006-12-12 23:36:14 +00002129 SqrtTerm = ConstantExpr::getTruncOrBitCast(SqrtVal, SqrtTerm->getType());
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002130
Chris Lattner53e677a2004-04-02 20:23:17 +00002131 Constant *NegB = ConstantExpr::getNeg(B);
2132 Constant *TwoA = ConstantExpr::getMul(A, Two);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002133
Chris Lattner53e677a2004-04-02 20:23:17 +00002134 // The divisions must be performed as signed divisions.
Chris Lattner53e677a2004-04-02 20:23:17 +00002135 Constant *Solution1 =
Reid Spencer1628cec2006-10-26 06:15:43 +00002136 ConstantExpr::getSDiv(ConstantExpr::getAdd(NegB, SqrtTerm), TwoA);
Chris Lattner53e677a2004-04-02 20:23:17 +00002137 Constant *Solution2 =
Reid Spencer1628cec2006-10-26 06:15:43 +00002138 ConstantExpr::getSDiv(ConstantExpr::getSub(NegB, SqrtTerm), TwoA);
Chris Lattner53e677a2004-04-02 20:23:17 +00002139 return std::make_pair(SCEVUnknown::get(Solution1),
2140 SCEVUnknown::get(Solution2));
2141}
2142
2143/// HowFarToZero - Return the number of times a backedge comparing the specified
2144/// value to zero will execute. If not computable, return UnknownValue
2145SCEVHandle ScalarEvolutionsImpl::HowFarToZero(SCEV *V, const Loop *L) {
2146 // If the value is a constant
2147 if (SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
2148 // If the value is already zero, the branch will execute zero times.
2149 if (C->getValue()->isNullValue()) return C;
2150 return UnknownValue; // Otherwise it will loop infinitely.
2151 }
2152
2153 SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
2154 if (!AddRec || AddRec->getLoop() != L)
2155 return UnknownValue;
2156
2157 if (AddRec->isAffine()) {
2158 // If this is an affine expression the execution count of this branch is
2159 // equal to:
2160 //
2161 // (0 - Start/Step) iff Start % Step == 0
2162 //
2163 // Get the initial value for the loop.
2164 SCEVHandle Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
Chris Lattner4a2b23e2004-10-11 04:07:27 +00002165 if (isa<SCEVCouldNotCompute>(Start)) return UnknownValue;
Chris Lattner53e677a2004-04-02 20:23:17 +00002166 SCEVHandle Step = AddRec->getOperand(1);
2167
2168 Step = getSCEVAtScope(Step, L->getParentLoop());
2169
2170 // Figure out if Start % Step == 0.
2171 // FIXME: We should add DivExpr and RemExpr operations to our AST.
2172 if (SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step)) {
2173 if (StepC->getValue()->equalsInt(1)) // N % 1 == 0
Chris Lattnerbac5b462005-03-09 05:34:41 +00002174 return SCEV::getNegativeSCEV(Start); // 0 - Start/1 == -Start
Chris Lattner53e677a2004-04-02 20:23:17 +00002175 if (StepC->getValue()->isAllOnesValue()) // N % -1 == 0
2176 return Start; // 0 - Start/-1 == Start
2177
2178 // Check to see if Start is divisible by SC with no remainder.
2179 if (SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start)) {
2180 ConstantInt *StartCC = StartC->getValue();
2181 Constant *StartNegC = ConstantExpr::getNeg(StartCC);
Reid Spencer0a783f72006-11-02 01:53:59 +00002182 Constant *Rem = ConstantExpr::getSRem(StartNegC, StepC->getValue());
Chris Lattner53e677a2004-04-02 20:23:17 +00002183 if (Rem->isNullValue()) {
Reid Spencer1628cec2006-10-26 06:15:43 +00002184 Constant *Result =ConstantExpr::getSDiv(StartNegC,StepC->getValue());
Chris Lattner53e677a2004-04-02 20:23:17 +00002185 return SCEVUnknown::get(Result);
2186 }
2187 }
2188 }
Chris Lattner42a75512007-01-15 02:27:26 +00002189 } else if (AddRec->isQuadratic() && AddRec->getType()->isInteger()) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002190 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
2191 // the quadratic equation to solve it.
2192 std::pair<SCEVHandle,SCEVHandle> Roots = SolveQuadraticEquation(AddRec);
2193 SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
2194 SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
2195 if (R1) {
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00002196#if 0
Bill Wendlinge8156192006-12-07 01:30:32 +00002197 cerr << "HFTZ: " << *V << " - sol#1: " << *R1
2198 << " sol#2: " << *R2 << "\n";
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00002199#endif
Chris Lattner53e677a2004-04-02 20:23:17 +00002200 // Pick the smallest positive root value.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002201 if (ConstantInt *CB =
2202 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
Reid Spencere4d87aa2006-12-23 06:05:41 +00002203 R1->getValue(), R2->getValue()))) {
Reid Spencer579dca12007-01-12 04:24:46 +00002204 if (CB->getZExtValue() == false)
Chris Lattner53e677a2004-04-02 20:23:17 +00002205 std::swap(R1, R2); // R1 is the minimum root now.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002206
Chris Lattner53e677a2004-04-02 20:23:17 +00002207 // We can only use this value if the chrec ends up with an exact zero
2208 // value at this index. When solving for "X*X != 5", for example, we
2209 // should not accept a root of 2.
2210 SCEVHandle Val = AddRec->evaluateAtIteration(R1);
2211 if (SCEVConstant *EvalVal = dyn_cast<SCEVConstant>(Val))
2212 if (EvalVal->getValue()->isNullValue())
2213 return R1; // We found a quadratic root!
2214 }
2215 }
2216 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002217
Chris Lattner53e677a2004-04-02 20:23:17 +00002218 return UnknownValue;
2219}
2220
2221/// HowFarToNonZero - Return the number of times a backedge checking the
2222/// specified value for nonzero will execute. If not computable, return
2223/// UnknownValue
2224SCEVHandle ScalarEvolutionsImpl::HowFarToNonZero(SCEV *V, const Loop *L) {
2225 // Loops that look like: while (X == 0) are very strange indeed. We don't
2226 // handle them yet except for the trivial case. This could be expanded in the
2227 // future as needed.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002228
Chris Lattner53e677a2004-04-02 20:23:17 +00002229 // If the value is a constant, check to see if it is known to be non-zero
2230 // already. If so, the backedge will execute zero times.
2231 if (SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
2232 Constant *Zero = Constant::getNullValue(C->getValue()->getType());
Reid Spencere4d87aa2006-12-23 06:05:41 +00002233 Constant *NonZero =
2234 ConstantExpr::getICmp(ICmpInst::ICMP_NE, C->getValue(), Zero);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002235 if (NonZero == ConstantInt::getTrue())
Chris Lattner53e677a2004-04-02 20:23:17 +00002236 return getSCEV(Zero);
2237 return UnknownValue; // Otherwise it will loop infinitely.
2238 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002239
Chris Lattner53e677a2004-04-02 20:23:17 +00002240 // We could implement others, but I really doubt anyone writes loops like
2241 // this, and if they did, they would already be constant folded.
2242 return UnknownValue;
2243}
2244
Chris Lattnerdb25de42005-08-15 23:33:51 +00002245/// HowManyLessThans - Return the number of times a backedge containing the
2246/// specified less-than comparison will execute. If not computable, return
2247/// UnknownValue.
2248SCEVHandle ScalarEvolutionsImpl::
2249HowManyLessThans(SCEV *LHS, SCEV *RHS, const Loop *L) {
2250 // Only handle: "ADDREC < LoopInvariant".
2251 if (!RHS->isLoopInvariant(L)) return UnknownValue;
2252
2253 SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS);
2254 if (!AddRec || AddRec->getLoop() != L)
2255 return UnknownValue;
2256
2257 if (AddRec->isAffine()) {
2258 // FORNOW: We only support unit strides.
2259 SCEVHandle One = SCEVUnknown::getIntegerSCEV(1, RHS->getType());
2260 if (AddRec->getOperand(1) != One)
2261 return UnknownValue;
2262
2263 // The number of iterations for "[n,+,1] < m", is m-n. However, we don't
2264 // know that m is >= n on input to the loop. If it is, the condition return
2265 // true zero times. What we really should return, for full generality, is
2266 // SMAX(0, m-n). Since we cannot check this, we will instead check for a
2267 // canonical loop form: most do-loops will have a check that dominates the
2268 // loop, that only enters the loop if [n-1]<m. If we can find this check,
2269 // we know that the SMAX will evaluate to m-n, because we know that m >= n.
2270
2271 // Search for the check.
2272 BasicBlock *Preheader = L->getLoopPreheader();
2273 BasicBlock *PreheaderDest = L->getHeader();
2274 if (Preheader == 0) return UnknownValue;
2275
2276 BranchInst *LoopEntryPredicate =
2277 dyn_cast<BranchInst>(Preheader->getTerminator());
2278 if (!LoopEntryPredicate) return UnknownValue;
2279
2280 // This might be a critical edge broken out. If the loop preheader ends in
2281 // an unconditional branch to the loop, check to see if the preheader has a
2282 // single predecessor, and if so, look for its terminator.
2283 while (LoopEntryPredicate->isUnconditional()) {
2284 PreheaderDest = Preheader;
2285 Preheader = Preheader->getSinglePredecessor();
2286 if (!Preheader) return UnknownValue; // Multiple preds.
2287
2288 LoopEntryPredicate =
2289 dyn_cast<BranchInst>(Preheader->getTerminator());
2290 if (!LoopEntryPredicate) return UnknownValue;
2291 }
2292
2293 // Now that we found a conditional branch that dominates the loop, check to
2294 // see if it is the comparison we are looking for.
Reid Spencere4d87aa2006-12-23 06:05:41 +00002295 if (ICmpInst *ICI = dyn_cast<ICmpInst>(LoopEntryPredicate->getCondition())){
2296 Value *PreCondLHS = ICI->getOperand(0);
2297 Value *PreCondRHS = ICI->getOperand(1);
2298 ICmpInst::Predicate Cond;
2299 if (LoopEntryPredicate->getSuccessor(0) == PreheaderDest)
2300 Cond = ICI->getPredicate();
2301 else
2302 Cond = ICI->getInversePredicate();
Chris Lattnerdb25de42005-08-15 23:33:51 +00002303
Reid Spencere4d87aa2006-12-23 06:05:41 +00002304 switch (Cond) {
2305 case ICmpInst::ICMP_UGT:
2306 std::swap(PreCondLHS, PreCondRHS);
2307 Cond = ICmpInst::ICMP_ULT;
Chris Lattnerdb25de42005-08-15 23:33:51 +00002308 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00002309 case ICmpInst::ICMP_SGT:
2310 std::swap(PreCondLHS, PreCondRHS);
2311 Cond = ICmpInst::ICMP_SLT;
2312 break;
2313 default: break;
Chris Lattnerdb25de42005-08-15 23:33:51 +00002314 }
Chris Lattnerdb25de42005-08-15 23:33:51 +00002315
Reid Spencere4d87aa2006-12-23 06:05:41 +00002316 if (Cond == ICmpInst::ICMP_SLT) {
Chris Lattner42a75512007-01-15 02:27:26 +00002317 if (PreCondLHS->getType()->isInteger()) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00002318 if (RHS != getSCEV(PreCondRHS))
2319 return UnknownValue; // Not a comparison against 'm'.
2320
2321 if (SCEV::getMinusSCEV(AddRec->getOperand(0), One)
2322 != getSCEV(PreCondLHS))
2323 return UnknownValue; // Not a comparison against 'n-1'.
2324 }
2325 else return UnknownValue;
2326 } else if (Cond == ICmpInst::ICMP_ULT)
2327 return UnknownValue;
2328
2329 // cerr << "Computed Loop Trip Count as: "
2330 // << // *SCEV::getMinusSCEV(RHS, AddRec->getOperand(0)) << "\n";
2331 return SCEV::getMinusSCEV(RHS, AddRec->getOperand(0));
2332 }
2333 else
2334 return UnknownValue;
Chris Lattnerdb25de42005-08-15 23:33:51 +00002335 }
2336
2337 return UnknownValue;
2338}
2339
Chris Lattner53e677a2004-04-02 20:23:17 +00002340/// getNumIterationsInRange - Return the number of iterations of this loop that
2341/// produce values in the specified constant range. Another way of looking at
2342/// this is that it returns the first iteration number where the value is not in
2343/// the condition, thus computing the exit count. If the iteration count can't
2344/// be computed, an instance of SCEVCouldNotCompute is returned.
Reid Spencere4d87aa2006-12-23 06:05:41 +00002345SCEVHandle SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range,
2346 bool isSigned) const {
Chris Lattner53e677a2004-04-02 20:23:17 +00002347 if (Range.isFullSet()) // Infinite loop.
2348 return new SCEVCouldNotCompute();
2349
2350 // If the start is a non-zero constant, shift the range to simplify things.
2351 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
2352 if (!SC->getValue()->isNullValue()) {
2353 std::vector<SCEVHandle> Operands(op_begin(), op_end());
Chris Lattnerb06432c2004-04-23 21:29:03 +00002354 Operands[0] = SCEVUnknown::getIntegerSCEV(0, SC->getType());
Chris Lattner53e677a2004-04-02 20:23:17 +00002355 SCEVHandle Shifted = SCEVAddRecExpr::get(Operands, getLoop());
2356 if (SCEVAddRecExpr *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted))
2357 return ShiftedAddRec->getNumIterationsInRange(
Reid Spencere4d87aa2006-12-23 06:05:41 +00002358 Range.subtract(SC->getValue()),isSigned);
Chris Lattner53e677a2004-04-02 20:23:17 +00002359 // This is strange and shouldn't happen.
2360 return new SCEVCouldNotCompute();
2361 }
2362
2363 // The only time we can solve this is when we have all constant indices.
2364 // Otherwise, we cannot determine the overflow conditions.
2365 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
2366 if (!isa<SCEVConstant>(getOperand(i)))
2367 return new SCEVCouldNotCompute();
2368
2369
2370 // Okay at this point we know that all elements of the chrec are constants and
2371 // that the start element is zero.
2372
2373 // First check to see if the range contains zero. If not, the first
2374 // iteration exits.
2375 ConstantInt *Zero = ConstantInt::get(getType(), 0);
Reid Spencere4d87aa2006-12-23 06:05:41 +00002376 if (!Range.contains(Zero, isSigned)) return SCEVConstant::get(Zero);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002377
Chris Lattner53e677a2004-04-02 20:23:17 +00002378 if (isAffine()) {
2379 // If this is an affine expression then we have this situation:
2380 // Solve {0,+,A} in Range === Ax in Range
2381
2382 // Since we know that zero is in the range, we know that the upper value of
2383 // the range must be the first possible exit value. Also note that we
2384 // already checked for a full range.
2385 ConstantInt *Upper = cast<ConstantInt>(Range.getUpper());
2386 ConstantInt *A = cast<SCEVConstant>(getOperand(1))->getValue();
2387 ConstantInt *One = ConstantInt::get(getType(), 1);
2388
2389 // The exit value should be (Upper+A-1)/A.
2390 Constant *ExitValue = Upper;
2391 if (A != One) {
2392 ExitValue = ConstantExpr::getSub(ConstantExpr::getAdd(Upper, A), One);
Reid Spencer1628cec2006-10-26 06:15:43 +00002393 ExitValue = ConstantExpr::getSDiv(ExitValue, A);
Chris Lattner53e677a2004-04-02 20:23:17 +00002394 }
2395 assert(isa<ConstantInt>(ExitValue) &&
2396 "Constant folding of integers not implemented?");
2397
2398 // Evaluate at the exit value. If we really did fall out of the valid
2399 // range, then we computed our trip count, otherwise wrap around or other
2400 // things must have happened.
2401 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue);
Reid Spencere4d87aa2006-12-23 06:05:41 +00002402 if (Range.contains(Val, isSigned))
Chris Lattner53e677a2004-04-02 20:23:17 +00002403 return new SCEVCouldNotCompute(); // Something strange happened
2404
2405 // Ensure that the previous value is in the range. This is a sanity check.
2406 assert(Range.contains(EvaluateConstantChrecAtConstant(this,
Reid Spencere4d87aa2006-12-23 06:05:41 +00002407 ConstantExpr::getSub(ExitValue, One)), isSigned) &&
Chris Lattner53e677a2004-04-02 20:23:17 +00002408 "Linear scev computation is off in a bad way!");
2409 return SCEVConstant::get(cast<ConstantInt>(ExitValue));
2410 } else if (isQuadratic()) {
2411 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
2412 // quadratic equation to solve it. To do this, we must frame our problem in
2413 // terms of figuring out when zero is crossed, instead of when
2414 // Range.getUpper() is crossed.
2415 std::vector<SCEVHandle> NewOps(op_begin(), op_end());
Chris Lattnerbac5b462005-03-09 05:34:41 +00002416 NewOps[0] = SCEV::getNegativeSCEV(SCEVUnknown::get(Range.getUpper()));
Chris Lattner53e677a2004-04-02 20:23:17 +00002417 SCEVHandle NewAddRec = SCEVAddRecExpr::get(NewOps, getLoop());
2418
2419 // Next, solve the constructed addrec
2420 std::pair<SCEVHandle,SCEVHandle> Roots =
2421 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec));
2422 SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
2423 SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
2424 if (R1) {
2425 // Pick the smallest positive root value.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002426 if (ConstantInt *CB =
2427 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
Reid Spencere4d87aa2006-12-23 06:05:41 +00002428 R1->getValue(), R2->getValue()))) {
Reid Spencer579dca12007-01-12 04:24:46 +00002429 if (CB->getZExtValue() == false)
Chris Lattner53e677a2004-04-02 20:23:17 +00002430 std::swap(R1, R2); // R1 is the minimum root now.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002431
Chris Lattner53e677a2004-04-02 20:23:17 +00002432 // Make sure the root is not off by one. The returned iteration should
2433 // not be in the range, but the previous one should be. When solving
2434 // for "X*X < 5", for example, we should not return a root of 2.
2435 ConstantInt *R1Val = EvaluateConstantChrecAtConstant(this,
2436 R1->getValue());
Reid Spencere4d87aa2006-12-23 06:05:41 +00002437 if (Range.contains(R1Val, isSigned)) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002438 // The next iteration must be out of the range...
2439 Constant *NextVal =
2440 ConstantExpr::getAdd(R1->getValue(),
2441 ConstantInt::get(R1->getType(), 1));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002442
Chris Lattner53e677a2004-04-02 20:23:17 +00002443 R1Val = EvaluateConstantChrecAtConstant(this, NextVal);
Reid Spencere4d87aa2006-12-23 06:05:41 +00002444 if (!Range.contains(R1Val, isSigned))
Chris Lattner53e677a2004-04-02 20:23:17 +00002445 return SCEVUnknown::get(NextVal);
2446 return new SCEVCouldNotCompute(); // Something strange happened
2447 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002448
Chris Lattner53e677a2004-04-02 20:23:17 +00002449 // If R1 was not in the range, then it is a good return value. Make
2450 // sure that R1-1 WAS in the range though, just in case.
2451 Constant *NextVal =
2452 ConstantExpr::getSub(R1->getValue(),
2453 ConstantInt::get(R1->getType(), 1));
2454 R1Val = EvaluateConstantChrecAtConstant(this, NextVal);
Reid Spencere4d87aa2006-12-23 06:05:41 +00002455 if (Range.contains(R1Val, isSigned))
Chris Lattner53e677a2004-04-02 20:23:17 +00002456 return R1;
2457 return new SCEVCouldNotCompute(); // Something strange happened
2458 }
2459 }
2460 }
2461
2462 // Fallback, if this is a general polynomial, figure out the progression
2463 // through brute force: evaluate until we find an iteration that fails the
2464 // test. This is likely to be slow, but getting an accurate trip count is
2465 // incredibly important, we will be able to simplify the exit test a lot, and
2466 // we are almost guaranteed to get a trip count in this case.
2467 ConstantInt *TestVal = ConstantInt::get(getType(), 0);
2468 ConstantInt *One = ConstantInt::get(getType(), 1);
2469 ConstantInt *EndVal = TestVal; // Stop when we wrap around.
2470 do {
2471 ++NumBruteForceEvaluations;
2472 SCEVHandle Val = evaluateAtIteration(SCEVConstant::get(TestVal));
2473 if (!isa<SCEVConstant>(Val)) // This shouldn't happen.
2474 return new SCEVCouldNotCompute();
2475
2476 // Check to see if we found the value!
Reid Spencere4d87aa2006-12-23 06:05:41 +00002477 if (!Range.contains(cast<SCEVConstant>(Val)->getValue(), isSigned))
Chris Lattner53e677a2004-04-02 20:23:17 +00002478 return SCEVConstant::get(TestVal);
2479
2480 // Increment to test the next index.
2481 TestVal = cast<ConstantInt>(ConstantExpr::getAdd(TestVal, One));
2482 } while (TestVal != EndVal);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002483
Chris Lattner53e677a2004-04-02 20:23:17 +00002484 return new SCEVCouldNotCompute();
2485}
2486
2487
2488
2489//===----------------------------------------------------------------------===//
2490// ScalarEvolution Class Implementation
2491//===----------------------------------------------------------------------===//
2492
2493bool ScalarEvolution::runOnFunction(Function &F) {
2494 Impl = new ScalarEvolutionsImpl(F, getAnalysis<LoopInfo>());
2495 return false;
2496}
2497
2498void ScalarEvolution::releaseMemory() {
2499 delete (ScalarEvolutionsImpl*)Impl;
2500 Impl = 0;
2501}
2502
2503void ScalarEvolution::getAnalysisUsage(AnalysisUsage &AU) const {
2504 AU.setPreservesAll();
Chris Lattner53e677a2004-04-02 20:23:17 +00002505 AU.addRequiredTransitive<LoopInfo>();
2506}
2507
2508SCEVHandle ScalarEvolution::getSCEV(Value *V) const {
2509 return ((ScalarEvolutionsImpl*)Impl)->getSCEV(V);
2510}
2511
Chris Lattnera0740fb2005-08-09 23:36:33 +00002512/// hasSCEV - Return true if the SCEV for this value has already been
2513/// computed.
2514bool ScalarEvolution::hasSCEV(Value *V) const {
Chris Lattner05bd3742005-08-10 00:59:40 +00002515 return ((ScalarEvolutionsImpl*)Impl)->hasSCEV(V);
Chris Lattnera0740fb2005-08-09 23:36:33 +00002516}
2517
2518
2519/// setSCEV - Insert the specified SCEV into the map of current SCEVs for
2520/// the specified value.
2521void ScalarEvolution::setSCEV(Value *V, const SCEVHandle &H) {
2522 ((ScalarEvolutionsImpl*)Impl)->setSCEV(V, H);
2523}
2524
2525
Chris Lattner53e677a2004-04-02 20:23:17 +00002526SCEVHandle ScalarEvolution::getIterationCount(const Loop *L) const {
2527 return ((ScalarEvolutionsImpl*)Impl)->getIterationCount(L);
2528}
2529
2530bool ScalarEvolution::hasLoopInvariantIterationCount(const Loop *L) const {
2531 return !isa<SCEVCouldNotCompute>(getIterationCount(L));
2532}
2533
2534SCEVHandle ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) const {
2535 return ((ScalarEvolutionsImpl*)Impl)->getSCEVAtScope(getSCEV(V), L);
2536}
2537
2538void ScalarEvolution::deleteInstructionFromRecords(Instruction *I) const {
2539 return ((ScalarEvolutionsImpl*)Impl)->deleteInstructionFromRecords(I);
2540}
2541
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002542static void PrintLoopInfo(std::ostream &OS, const ScalarEvolution *SE,
Chris Lattner53e677a2004-04-02 20:23:17 +00002543 const Loop *L) {
2544 // Print all inner loops first
2545 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
2546 PrintLoopInfo(OS, SE, *I);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002547
Bill Wendlinge8156192006-12-07 01:30:32 +00002548 cerr << "Loop " << L->getHeader()->getName() << ": ";
Chris Lattnerf1ab4b42004-04-18 22:14:10 +00002549
2550 std::vector<BasicBlock*> ExitBlocks;
2551 L->getExitBlocks(ExitBlocks);
2552 if (ExitBlocks.size() != 1)
Bill Wendlinge8156192006-12-07 01:30:32 +00002553 cerr << "<multiple exits> ";
Chris Lattner53e677a2004-04-02 20:23:17 +00002554
2555 if (SE->hasLoopInvariantIterationCount(L)) {
Bill Wendlinge8156192006-12-07 01:30:32 +00002556 cerr << *SE->getIterationCount(L) << " iterations! ";
Chris Lattner53e677a2004-04-02 20:23:17 +00002557 } else {
Bill Wendlinge8156192006-12-07 01:30:32 +00002558 cerr << "Unpredictable iteration count. ";
Chris Lattner53e677a2004-04-02 20:23:17 +00002559 }
2560
Bill Wendlinge8156192006-12-07 01:30:32 +00002561 cerr << "\n";
Chris Lattner53e677a2004-04-02 20:23:17 +00002562}
2563
Reid Spencerce9653c2004-12-07 04:03:45 +00002564void ScalarEvolution::print(std::ostream &OS, const Module* ) const {
Chris Lattner53e677a2004-04-02 20:23:17 +00002565 Function &F = ((ScalarEvolutionsImpl*)Impl)->F;
2566 LoopInfo &LI = ((ScalarEvolutionsImpl*)Impl)->LI;
2567
2568 OS << "Classifying expressions for: " << F.getName() << "\n";
2569 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
Chris Lattner42a75512007-01-15 02:27:26 +00002570 if (I->getType()->isInteger()) {
Chris Lattner6ffe5512004-04-27 15:13:33 +00002571 OS << *I;
Chris Lattner53e677a2004-04-02 20:23:17 +00002572 OS << " --> ";
Chris Lattner6ffe5512004-04-27 15:13:33 +00002573 SCEVHandle SV = getSCEV(&*I);
Chris Lattner53e677a2004-04-02 20:23:17 +00002574 SV->print(OS);
2575 OS << "\t\t";
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002576
Chris Lattner42a75512007-01-15 02:27:26 +00002577 if ((*I).getType()->isInteger()) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002578 ConstantRange Bounds = SV->getValueRange();
2579 if (!Bounds.isFullSet())
2580 OS << "Bounds: " << Bounds << " ";
2581 }
2582
Chris Lattner6ffe5512004-04-27 15:13:33 +00002583 if (const Loop *L = LI.getLoopFor((*I).getParent())) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002584 OS << "Exits: ";
Chris Lattner6ffe5512004-04-27 15:13:33 +00002585 SCEVHandle ExitValue = getSCEVAtScope(&*I, L->getParentLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00002586 if (isa<SCEVCouldNotCompute>(ExitValue)) {
2587 OS << "<<Unknown>>";
2588 } else {
2589 OS << *ExitValue;
2590 }
2591 }
2592
2593
2594 OS << "\n";
2595 }
2596
2597 OS << "Determining loop execution counts for: " << F.getName() << "\n";
2598 for (LoopInfo::iterator I = LI.begin(), E = LI.end(); I != E; ++I)
2599 PrintLoopInfo(OS, this, *I);
2600}
2601