blob: 5bae18cc4c33ab8c2932ba90896357349c209f11 [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}
Devang Patel19974732007-05-03 01:11:54 +0000108char ScalarEvolution::ID = 0;
Chris Lattner53e677a2004-04-02 20:23:17 +0000109
110//===----------------------------------------------------------------------===//
111// SCEV class definitions
112//===----------------------------------------------------------------------===//
113
114//===----------------------------------------------------------------------===//
115// Implementation of the SCEV class.
116//
Chris Lattner53e677a2004-04-02 20:23:17 +0000117SCEV::~SCEV() {}
118void SCEV::dump() const {
Bill Wendlinge8156192006-12-07 01:30:32 +0000119 print(cerr);
Chris Lattner53e677a2004-04-02 20:23:17 +0000120}
121
122/// getValueRange - Return the tightest constant bounds that this value is
123/// known to have. This method is only valid on integer SCEV objects.
124ConstantRange SCEV::getValueRange() const {
125 const Type *Ty = getType();
Chris Lattner42a75512007-01-15 02:27:26 +0000126 assert(Ty->isInteger() && "Can't get range for a non-integer SCEV!");
Chris Lattner53e677a2004-04-02 20:23:17 +0000127 // Default to a full range if no better information is available.
Reid Spencerc6aedf72007-02-28 22:03:51 +0000128 return ConstantRange(getBitWidth());
Chris Lattner53e677a2004-04-02 20:23:17 +0000129}
130
Reid Spencer581b0d42007-02-28 19:57:34 +0000131uint32_t SCEV::getBitWidth() const {
132 if (const IntegerType* ITy = dyn_cast<IntegerType>(getType()))
133 return ITy->getBitWidth();
134 return 0;
135}
136
Chris Lattner53e677a2004-04-02 20:23:17 +0000137
138SCEVCouldNotCompute::SCEVCouldNotCompute() : SCEV(scCouldNotCompute) {}
139
140bool SCEVCouldNotCompute::isLoopInvariant(const Loop *L) const {
141 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
Misha Brukmanbb2aff12004-04-05 19:00:46 +0000142 return false;
Chris Lattner53e677a2004-04-02 20:23:17 +0000143}
144
145const Type *SCEVCouldNotCompute::getType() const {
146 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
Misha Brukmanbb2aff12004-04-05 19:00:46 +0000147 return 0;
Chris Lattner53e677a2004-04-02 20:23:17 +0000148}
149
150bool SCEVCouldNotCompute::hasComputableLoopEvolution(const Loop *L) const {
151 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
152 return false;
153}
154
Chris Lattner4dc534c2005-02-13 04:37:18 +0000155SCEVHandle SCEVCouldNotCompute::
156replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
157 const SCEVHandle &Conc) const {
158 return this;
159}
160
Chris Lattner53e677a2004-04-02 20:23:17 +0000161void SCEVCouldNotCompute::print(std::ostream &OS) const {
162 OS << "***COULDNOTCOMPUTE***";
163}
164
165bool SCEVCouldNotCompute::classof(const SCEV *S) {
166 return S->getSCEVType() == scCouldNotCompute;
167}
168
169
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000170// SCEVConstants - Only allow the creation of one SCEVConstant for any
171// particular value. Don't use a SCEVHandle here, or else the object will
172// never be deleted!
Chris Lattnerb3364092006-10-04 21:49:37 +0000173static ManagedStatic<std::map<ConstantInt*, SCEVConstant*> > SCEVConstants;
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000174
Chris Lattner53e677a2004-04-02 20:23:17 +0000175
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000176SCEVConstant::~SCEVConstant() {
Chris Lattnerb3364092006-10-04 21:49:37 +0000177 SCEVConstants->erase(V);
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000178}
Chris Lattner53e677a2004-04-02 20:23:17 +0000179
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000180SCEVHandle SCEVConstant::get(ConstantInt *V) {
Chris Lattnerb3364092006-10-04 21:49:37 +0000181 SCEVConstant *&R = (*SCEVConstants)[V];
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000182 if (R == 0) R = new SCEVConstant(V);
183 return R;
184}
Chris Lattner53e677a2004-04-02 20:23:17 +0000185
Dan Gohman9a6ae962007-07-09 15:25:17 +0000186SCEVHandle SCEVConstant::get(const APInt& Val) {
187 return get(ConstantInt::get(Val));
188}
189
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000190ConstantRange SCEVConstant::getValueRange() const {
Reid Spencerdc5c1592007-02-28 18:57:32 +0000191 return ConstantRange(V->getValue());
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000192}
Chris Lattner53e677a2004-04-02 20:23:17 +0000193
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000194const Type *SCEVConstant::getType() const { return V->getType(); }
Chris Lattner53e677a2004-04-02 20:23:17 +0000195
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000196void SCEVConstant::print(std::ostream &OS) const {
197 WriteAsOperand(OS, V, false);
198}
Chris Lattner53e677a2004-04-02 20:23:17 +0000199
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000200// SCEVTruncates - Only allow the creation of one SCEVTruncateExpr for any
201// particular input. Don't use a SCEVHandle here, or else the object will
202// never be deleted!
Chris Lattnerb3364092006-10-04 21:49:37 +0000203static ManagedStatic<std::map<std::pair<SCEV*, const Type*>,
204 SCEVTruncateExpr*> > SCEVTruncates;
Chris Lattner53e677a2004-04-02 20:23:17 +0000205
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000206SCEVTruncateExpr::SCEVTruncateExpr(const SCEVHandle &op, const Type *ty)
207 : SCEV(scTruncate), Op(op), Ty(ty) {
Chris Lattner42a75512007-01-15 02:27:26 +0000208 assert(Op->getType()->isInteger() && Ty->isInteger() &&
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000209 "Cannot truncate non-integer value!");
Reid Spencere7ca0422007-01-08 01:26:33 +0000210 assert(Op->getType()->getPrimitiveSizeInBits() > Ty->getPrimitiveSizeInBits()
211 && "This is not a truncating conversion!");
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000212}
Chris Lattner53e677a2004-04-02 20:23:17 +0000213
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000214SCEVTruncateExpr::~SCEVTruncateExpr() {
Chris Lattnerb3364092006-10-04 21:49:37 +0000215 SCEVTruncates->erase(std::make_pair(Op, Ty));
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000216}
Chris Lattner53e677a2004-04-02 20:23:17 +0000217
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000218ConstantRange SCEVTruncateExpr::getValueRange() const {
Reid Spencerc6aedf72007-02-28 22:03:51 +0000219 return getOperand()->getValueRange().truncate(getBitWidth());
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000220}
Chris Lattner53e677a2004-04-02 20:23:17 +0000221
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000222void SCEVTruncateExpr::print(std::ostream &OS) const {
223 OS << "(truncate " << *Op << " to " << *Ty << ")";
224}
225
226// SCEVZeroExtends - Only allow the creation of one SCEVZeroExtendExpr for any
227// particular input. Don't use a SCEVHandle here, or else the object will never
228// be deleted!
Chris Lattnerb3364092006-10-04 21:49:37 +0000229static ManagedStatic<std::map<std::pair<SCEV*, const Type*>,
230 SCEVZeroExtendExpr*> > SCEVZeroExtends;
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000231
232SCEVZeroExtendExpr::SCEVZeroExtendExpr(const SCEVHandle &op, const Type *ty)
Reid Spencer48d8a702006-11-01 21:53:12 +0000233 : SCEV(scZeroExtend), Op(op), Ty(ty) {
Chris Lattner42a75512007-01-15 02:27:26 +0000234 assert(Op->getType()->isInteger() && Ty->isInteger() &&
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000235 "Cannot zero extend non-integer value!");
Reid Spencere7ca0422007-01-08 01:26:33 +0000236 assert(Op->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits()
237 && "This is not an extending conversion!");
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000238}
239
240SCEVZeroExtendExpr::~SCEVZeroExtendExpr() {
Chris Lattnerb3364092006-10-04 21:49:37 +0000241 SCEVZeroExtends->erase(std::make_pair(Op, Ty));
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000242}
243
244ConstantRange SCEVZeroExtendExpr::getValueRange() const {
Reid Spencerc6aedf72007-02-28 22:03:51 +0000245 return getOperand()->getValueRange().zeroExtend(getBitWidth());
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000246}
247
248void SCEVZeroExtendExpr::print(std::ostream &OS) const {
249 OS << "(zeroextend " << *Op << " to " << *Ty << ")";
250}
251
Dan Gohmand19534a2007-06-15 14:38:12 +0000252// SCEVSignExtends - Only allow the creation of one SCEVSignExtendExpr for any
253// particular input. Don't use a SCEVHandle here, or else the object will never
254// be deleted!
255static ManagedStatic<std::map<std::pair<SCEV*, const Type*>,
256 SCEVSignExtendExpr*> > SCEVSignExtends;
257
258SCEVSignExtendExpr::SCEVSignExtendExpr(const SCEVHandle &op, const Type *ty)
259 : SCEV(scSignExtend), Op(op), Ty(ty) {
260 assert(Op->getType()->isInteger() && Ty->isInteger() &&
261 "Cannot sign extend non-integer value!");
262 assert(Op->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits()
263 && "This is not an extending conversion!");
264}
265
266SCEVSignExtendExpr::~SCEVSignExtendExpr() {
267 SCEVSignExtends->erase(std::make_pair(Op, Ty));
268}
269
270ConstantRange SCEVSignExtendExpr::getValueRange() const {
271 return getOperand()->getValueRange().signExtend(getBitWidth());
272}
273
274void SCEVSignExtendExpr::print(std::ostream &OS) const {
275 OS << "(signextend " << *Op << " to " << *Ty << ")";
276}
277
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000278// SCEVCommExprs - Only allow the creation of one SCEVCommutativeExpr for any
279// particular input. Don't use a SCEVHandle here, or else the object will never
280// be deleted!
Chris Lattnerb3364092006-10-04 21:49:37 +0000281static ManagedStatic<std::map<std::pair<unsigned, std::vector<SCEV*> >,
282 SCEVCommutativeExpr*> > SCEVCommExprs;
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000283
284SCEVCommutativeExpr::~SCEVCommutativeExpr() {
Chris Lattnerb3364092006-10-04 21:49:37 +0000285 SCEVCommExprs->erase(std::make_pair(getSCEVType(),
286 std::vector<SCEV*>(Operands.begin(),
287 Operands.end())));
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000288}
289
290void SCEVCommutativeExpr::print(std::ostream &OS) const {
291 assert(Operands.size() > 1 && "This plus expr shouldn't exist!");
292 const char *OpStr = getOperationStr();
293 OS << "(" << *Operands[0];
294 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
295 OS << OpStr << *Operands[i];
296 OS << ")";
297}
298
Chris Lattner4dc534c2005-02-13 04:37:18 +0000299SCEVHandle SCEVCommutativeExpr::
300replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
301 const SCEVHandle &Conc) const {
302 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
303 SCEVHandle H = getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc);
304 if (H != getOperand(i)) {
305 std::vector<SCEVHandle> NewOps;
306 NewOps.reserve(getNumOperands());
307 for (unsigned j = 0; j != i; ++j)
308 NewOps.push_back(getOperand(j));
309 NewOps.push_back(H);
310 for (++i; i != e; ++i)
311 NewOps.push_back(getOperand(i)->
312 replaceSymbolicValuesWithConcrete(Sym, Conc));
313
314 if (isa<SCEVAddExpr>(this))
315 return SCEVAddExpr::get(NewOps);
316 else if (isa<SCEVMulExpr>(this))
317 return SCEVMulExpr::get(NewOps);
318 else
319 assert(0 && "Unknown commutative expr!");
320 }
321 }
322 return this;
323}
324
325
Chris Lattner60a05cc2006-04-01 04:48:52 +0000326// SCEVSDivs - Only allow the creation of one SCEVSDivExpr for any particular
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000327// input. Don't use a SCEVHandle here, or else the object will never be
328// deleted!
Chris Lattnerb3364092006-10-04 21:49:37 +0000329static ManagedStatic<std::map<std::pair<SCEV*, SCEV*>,
330 SCEVSDivExpr*> > SCEVSDivs;
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000331
Chris Lattner60a05cc2006-04-01 04:48:52 +0000332SCEVSDivExpr::~SCEVSDivExpr() {
Chris Lattnerb3364092006-10-04 21:49:37 +0000333 SCEVSDivs->erase(std::make_pair(LHS, RHS));
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000334}
335
Chris Lattner60a05cc2006-04-01 04:48:52 +0000336void SCEVSDivExpr::print(std::ostream &OS) const {
337 OS << "(" << *LHS << " /s " << *RHS << ")";
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000338}
339
Chris Lattner60a05cc2006-04-01 04:48:52 +0000340const Type *SCEVSDivExpr::getType() const {
Reid Spencerc5b206b2006-12-31 05:48:39 +0000341 return LHS->getType();
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000342}
343
344// SCEVAddRecExprs - Only allow the creation of one SCEVAddRecExpr for any
345// particular input. Don't use a SCEVHandle here, or else the object will never
346// be deleted!
Chris Lattnerb3364092006-10-04 21:49:37 +0000347static ManagedStatic<std::map<std::pair<const Loop *, std::vector<SCEV*> >,
348 SCEVAddRecExpr*> > SCEVAddRecExprs;
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000349
350SCEVAddRecExpr::~SCEVAddRecExpr() {
Chris Lattnerb3364092006-10-04 21:49:37 +0000351 SCEVAddRecExprs->erase(std::make_pair(L,
352 std::vector<SCEV*>(Operands.begin(),
353 Operands.end())));
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000354}
355
Chris Lattner4dc534c2005-02-13 04:37:18 +0000356SCEVHandle SCEVAddRecExpr::
357replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
358 const SCEVHandle &Conc) const {
359 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
360 SCEVHandle H = getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc);
361 if (H != getOperand(i)) {
362 std::vector<SCEVHandle> NewOps;
363 NewOps.reserve(getNumOperands());
364 for (unsigned j = 0; j != i; ++j)
365 NewOps.push_back(getOperand(j));
366 NewOps.push_back(H);
367 for (++i; i != e; ++i)
368 NewOps.push_back(getOperand(i)->
369 replaceSymbolicValuesWithConcrete(Sym, Conc));
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000370
Chris Lattner4dc534c2005-02-13 04:37:18 +0000371 return get(NewOps, L);
372 }
373 }
374 return this;
375}
376
377
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000378bool SCEVAddRecExpr::isLoopInvariant(const Loop *QueryLoop) const {
379 // This recurrence is invariant w.r.t to QueryLoop iff QueryLoop doesn't
Chris Lattnerff2006a2005-08-16 00:37:01 +0000380 // contain L and if the start is invariant.
381 return !QueryLoop->contains(L->getHeader()) &&
382 getOperand(0)->isLoopInvariant(QueryLoop);
Chris Lattner53e677a2004-04-02 20:23:17 +0000383}
384
385
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000386void SCEVAddRecExpr::print(std::ostream &OS) const {
387 OS << "{" << *Operands[0];
388 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
389 OS << ",+," << *Operands[i];
390 OS << "}<" << L->getHeader()->getName() + ">";
391}
Chris Lattner53e677a2004-04-02 20:23:17 +0000392
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000393// SCEVUnknowns - Only allow the creation of one SCEVUnknown for any particular
394// value. Don't use a SCEVHandle here, or else the object will never be
395// deleted!
Chris Lattnerb3364092006-10-04 21:49:37 +0000396static ManagedStatic<std::map<Value*, SCEVUnknown*> > SCEVUnknowns;
Chris Lattner53e677a2004-04-02 20:23:17 +0000397
Chris Lattnerb3364092006-10-04 21:49:37 +0000398SCEVUnknown::~SCEVUnknown() { SCEVUnknowns->erase(V); }
Chris Lattner53e677a2004-04-02 20:23:17 +0000399
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000400bool SCEVUnknown::isLoopInvariant(const Loop *L) const {
401 // All non-instruction values are loop invariant. All instructions are loop
402 // invariant if they are not contained in the specified loop.
403 if (Instruction *I = dyn_cast<Instruction>(V))
404 return !L->contains(I->getParent());
405 return true;
406}
Chris Lattner53e677a2004-04-02 20:23:17 +0000407
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000408const Type *SCEVUnknown::getType() const {
409 return V->getType();
410}
Chris Lattner53e677a2004-04-02 20:23:17 +0000411
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000412void SCEVUnknown::print(std::ostream &OS) const {
413 WriteAsOperand(OS, V, false);
Chris Lattner53e677a2004-04-02 20:23:17 +0000414}
415
Chris Lattner8d741b82004-06-20 06:23:15 +0000416//===----------------------------------------------------------------------===//
417// SCEV Utilities
418//===----------------------------------------------------------------------===//
419
420namespace {
421 /// SCEVComplexityCompare - Return true if the complexity of the LHS is less
422 /// than the complexity of the RHS. This comparator is used to canonicalize
423 /// expressions.
Chris Lattner95255282006-06-28 23:17:24 +0000424 struct VISIBILITY_HIDDEN SCEVComplexityCompare {
Chris Lattner8d741b82004-06-20 06:23:15 +0000425 bool operator()(SCEV *LHS, SCEV *RHS) {
426 return LHS->getSCEVType() < RHS->getSCEVType();
427 }
428 };
429}
430
431/// GroupByComplexity - Given a list of SCEV objects, order them by their
432/// complexity, and group objects of the same complexity together by value.
433/// When this routine is finished, we know that any duplicates in the vector are
434/// consecutive and that complexity is monotonically increasing.
435///
436/// Note that we go take special precautions to ensure that we get determinstic
437/// results from this routine. In other words, we don't want the results of
438/// this to depend on where the addresses of various SCEV objects happened to
439/// land in memory.
440///
441static void GroupByComplexity(std::vector<SCEVHandle> &Ops) {
442 if (Ops.size() < 2) return; // Noop
443 if (Ops.size() == 2) {
444 // This is the common case, which also happens to be trivially simple.
445 // Special case it.
446 if (Ops[0]->getSCEVType() > Ops[1]->getSCEVType())
447 std::swap(Ops[0], Ops[1]);
448 return;
449 }
450
451 // Do the rough sort by complexity.
452 std::sort(Ops.begin(), Ops.end(), SCEVComplexityCompare());
453
454 // Now that we are sorted by complexity, group elements of the same
455 // complexity. Note that this is, at worst, N^2, but the vector is likely to
456 // be extremely short in practice. Note that we take this approach because we
457 // do not want to depend on the addresses of the objects we are grouping.
Chris Lattner2d584522004-06-20 17:01:44 +0000458 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
Chris Lattner8d741b82004-06-20 06:23:15 +0000459 SCEV *S = Ops[i];
460 unsigned Complexity = S->getSCEVType();
461
462 // If there are any objects of the same complexity and same value as this
463 // one, group them.
464 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
465 if (Ops[j] == S) { // Found a duplicate.
466 // Move it to immediately after i'th element.
467 std::swap(Ops[i+1], Ops[j]);
468 ++i; // no need to rescan it.
Chris Lattner541ad5e2004-06-20 20:32:16 +0000469 if (i == e-2) return; // Done!
Chris Lattner8d741b82004-06-20 06:23:15 +0000470 }
471 }
472 }
473}
474
Chris Lattner53e677a2004-04-02 20:23:17 +0000475
Chris Lattner53e677a2004-04-02 20:23:17 +0000476
477//===----------------------------------------------------------------------===//
478// Simple SCEV method implementations
479//===----------------------------------------------------------------------===//
480
481/// getIntegerSCEV - Given an integer or FP type, create a constant for the
482/// specified signed integer value and return a SCEV for the constant.
Chris Lattnerb06432c2004-04-23 21:29:03 +0000483SCEVHandle SCEVUnknown::getIntegerSCEV(int Val, const Type *Ty) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000484 Constant *C;
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000485 if (Val == 0)
Chris Lattner53e677a2004-04-02 20:23:17 +0000486 C = Constant::getNullValue(Ty);
487 else if (Ty->isFloatingPoint())
488 C = ConstantFP::get(Ty, Val);
Reid Spencere4d87aa2006-12-23 06:05:41 +0000489 else
Reid Spencerb83eb642006-10-20 07:07:24 +0000490 C = ConstantInt::get(Ty, Val);
Chris Lattner53e677a2004-04-02 20:23:17 +0000491 return SCEVUnknown::get(C);
492}
493
494/// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion of the
495/// input value to the specified type. If the type must be extended, it is zero
496/// extended.
497static SCEVHandle getTruncateOrZeroExtend(const SCEVHandle &V, const Type *Ty) {
498 const Type *SrcTy = V->getType();
Chris Lattner42a75512007-01-15 02:27:26 +0000499 assert(SrcTy->isInteger() && Ty->isInteger() &&
Chris Lattner53e677a2004-04-02 20:23:17 +0000500 "Cannot truncate or zero extend with non-integer arguments!");
Reid Spencere7ca0422007-01-08 01:26:33 +0000501 if (SrcTy->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
Chris Lattner53e677a2004-04-02 20:23:17 +0000502 return V; // No conversion
Reid Spencere7ca0422007-01-08 01:26:33 +0000503 if (SrcTy->getPrimitiveSizeInBits() > Ty->getPrimitiveSizeInBits())
Chris Lattner53e677a2004-04-02 20:23:17 +0000504 return SCEVTruncateExpr::get(V, Ty);
505 return SCEVZeroExtendExpr::get(V, Ty);
506}
507
508/// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V
509///
Chris Lattnerbac5b462005-03-09 05:34:41 +0000510SCEVHandle SCEV::getNegativeSCEV(const SCEVHandle &V) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000511 if (SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
512 return SCEVUnknown::get(ConstantExpr::getNeg(VC->getValue()));
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000513
Chris Lattnerb06432c2004-04-23 21:29:03 +0000514 return SCEVMulExpr::get(V, SCEVUnknown::getIntegerSCEV(-1, V->getType()));
Chris Lattner53e677a2004-04-02 20:23:17 +0000515}
516
517/// getMinusSCEV - Return a SCEV corresponding to LHS - RHS.
518///
Chris Lattnerbac5b462005-03-09 05:34:41 +0000519SCEVHandle SCEV::getMinusSCEV(const SCEVHandle &LHS, const SCEVHandle &RHS) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000520 // X - Y --> X + -Y
Chris Lattnerbac5b462005-03-09 05:34:41 +0000521 return SCEVAddExpr::get(LHS, SCEV::getNegativeSCEV(RHS));
Chris Lattner53e677a2004-04-02 20:23:17 +0000522}
523
524
Chris Lattner53e677a2004-04-02 20:23:17 +0000525/// PartialFact - Compute V!/(V-NumSteps)!
526static SCEVHandle PartialFact(SCEVHandle V, unsigned NumSteps) {
527 // Handle this case efficiently, it is common to have constant iteration
528 // counts while computing loop exit values.
529 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(V)) {
Zhou Sheng414de4d2007-04-07 17:48:27 +0000530 const APInt& Val = SC->getValue()->getValue();
Reid Spencerdc5c1592007-02-28 18:57:32 +0000531 APInt Result(Val.getBitWidth(), 1);
Chris Lattner53e677a2004-04-02 20:23:17 +0000532 for (; NumSteps; --NumSteps)
533 Result *= Val-(NumSteps-1);
Dan Gohman9a6ae962007-07-09 15:25:17 +0000534 return SCEVConstant::get(Result);
Chris Lattner53e677a2004-04-02 20:23:17 +0000535 }
536
537 const Type *Ty = V->getType();
538 if (NumSteps == 0)
Chris Lattnerb06432c2004-04-23 21:29:03 +0000539 return SCEVUnknown::getIntegerSCEV(1, Ty);
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000540
Chris Lattner53e677a2004-04-02 20:23:17 +0000541 SCEVHandle Result = V;
542 for (unsigned i = 1; i != NumSteps; ++i)
Chris Lattnerbac5b462005-03-09 05:34:41 +0000543 Result = SCEVMulExpr::get(Result, SCEV::getMinusSCEV(V,
Chris Lattnerb06432c2004-04-23 21:29:03 +0000544 SCEVUnknown::getIntegerSCEV(i, Ty)));
Chris Lattner53e677a2004-04-02 20:23:17 +0000545 return Result;
546}
547
548
549/// evaluateAtIteration - Return the value of this chain of recurrences at
550/// the specified iteration number. We can evaluate this recurrence by
551/// multiplying each element in the chain by the binomial coefficient
552/// corresponding to it. In other words, we can evaluate {A,+,B,+,C,+,D} as:
553///
554/// A*choose(It, 0) + B*choose(It, 1) + C*choose(It, 2) + D*choose(It, 3)
555///
556/// FIXME/VERIFY: I don't trust that this is correct in the face of overflow.
557/// Is the binomial equation safe using modular arithmetic??
558///
559SCEVHandle SCEVAddRecExpr::evaluateAtIteration(SCEVHandle It) const {
560 SCEVHandle Result = getStart();
561 int Divisor = 1;
562 const Type *Ty = It->getType();
563 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
564 SCEVHandle BC = PartialFact(It, i);
565 Divisor *= i;
Chris Lattner60a05cc2006-04-01 04:48:52 +0000566 SCEVHandle Val = SCEVSDivExpr::get(SCEVMulExpr::get(BC, getOperand(i)),
Chris Lattnerb06432c2004-04-23 21:29:03 +0000567 SCEVUnknown::getIntegerSCEV(Divisor,Ty));
Chris Lattner53e677a2004-04-02 20:23:17 +0000568 Result = SCEVAddExpr::get(Result, Val);
569 }
570 return Result;
571}
572
573
574//===----------------------------------------------------------------------===//
575// SCEV Expression folder implementations
576//===----------------------------------------------------------------------===//
577
578SCEVHandle SCEVTruncateExpr::get(const SCEVHandle &Op, const Type *Ty) {
579 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
Reid Spencer7858b332006-12-05 19:14:13 +0000580 return SCEVUnknown::get(
Reid Spencer315d0552006-12-05 22:39:58 +0000581 ConstantExpr::getTrunc(SC->getValue(), Ty));
Chris Lattner53e677a2004-04-02 20:23:17 +0000582
583 // If the input value is a chrec scev made out of constants, truncate
584 // all of the constants.
585 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
586 std::vector<SCEVHandle> Operands;
587 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
588 // FIXME: This should allow truncation of other expression types!
589 if (isa<SCEVConstant>(AddRec->getOperand(i)))
590 Operands.push_back(get(AddRec->getOperand(i), Ty));
591 else
592 break;
593 if (Operands.size() == AddRec->getNumOperands())
594 return SCEVAddRecExpr::get(Operands, AddRec->getLoop());
595 }
596
Chris Lattnerb3364092006-10-04 21:49:37 +0000597 SCEVTruncateExpr *&Result = (*SCEVTruncates)[std::make_pair(Op, Ty)];
Chris Lattner53e677a2004-04-02 20:23:17 +0000598 if (Result == 0) Result = new SCEVTruncateExpr(Op, Ty);
599 return Result;
600}
601
602SCEVHandle SCEVZeroExtendExpr::get(const SCEVHandle &Op, const Type *Ty) {
603 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
Reid Spencer7858b332006-12-05 19:14:13 +0000604 return SCEVUnknown::get(
Reid Spencerd977d862006-12-12 23:36:14 +0000605 ConstantExpr::getZExt(SC->getValue(), Ty));
Chris Lattner53e677a2004-04-02 20:23:17 +0000606
607 // FIXME: If the input value is a chrec scev, and we can prove that the value
608 // did not overflow the old, smaller, value, we can zero extend all of the
609 // operands (often constants). This would allow analysis of something like
610 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
611
Chris Lattnerb3364092006-10-04 21:49:37 +0000612 SCEVZeroExtendExpr *&Result = (*SCEVZeroExtends)[std::make_pair(Op, Ty)];
Chris Lattner53e677a2004-04-02 20:23:17 +0000613 if (Result == 0) Result = new SCEVZeroExtendExpr(Op, Ty);
614 return Result;
615}
616
Dan Gohmand19534a2007-06-15 14:38:12 +0000617SCEVHandle SCEVSignExtendExpr::get(const SCEVHandle &Op, const Type *Ty) {
618 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
619 return SCEVUnknown::get(
620 ConstantExpr::getSExt(SC->getValue(), Ty));
621
622 // FIXME: If the input value is a chrec scev, and we can prove that the value
623 // did not overflow the old, smaller, value, we can sign extend all of the
624 // operands (often constants). This would allow analysis of something like
625 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; }
626
627 SCEVSignExtendExpr *&Result = (*SCEVSignExtends)[std::make_pair(Op, Ty)];
628 if (Result == 0) Result = new SCEVSignExtendExpr(Op, Ty);
629 return Result;
630}
631
Chris Lattner53e677a2004-04-02 20:23:17 +0000632// get - Get a canonical add expression, or something simpler if possible.
633SCEVHandle SCEVAddExpr::get(std::vector<SCEVHandle> &Ops) {
634 assert(!Ops.empty() && "Cannot get empty add!");
Chris Lattner627018b2004-04-07 16:16:11 +0000635 if (Ops.size() == 1) return Ops[0];
Chris Lattner53e677a2004-04-02 20:23:17 +0000636
637 // Sort by complexity, this groups all similar expression types together.
Chris Lattner8d741b82004-06-20 06:23:15 +0000638 GroupByComplexity(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +0000639
640 // If there are any constants, fold them together.
641 unsigned Idx = 0;
642 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
643 ++Idx;
Chris Lattner627018b2004-04-07 16:16:11 +0000644 assert(Idx < Ops.size());
Chris Lattner53e677a2004-04-02 20:23:17 +0000645 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
646 // We found two constants, fold them together!
Zhou Shengfdc1e162007-04-07 17:40:57 +0000647 Constant *Fold = ConstantInt::get(LHSC->getValue()->getValue() +
648 RHSC->getValue()->getValue());
Chris Lattner53e677a2004-04-02 20:23:17 +0000649 if (ConstantInt *CI = dyn_cast<ConstantInt>(Fold)) {
650 Ops[0] = SCEVConstant::get(CI);
651 Ops.erase(Ops.begin()+1); // Erase the folded element
652 if (Ops.size() == 1) return Ops[0];
Chris Lattner7ffc07d2005-02-26 18:50:19 +0000653 LHSC = cast<SCEVConstant>(Ops[0]);
Chris Lattner53e677a2004-04-02 20:23:17 +0000654 } else {
655 // If we couldn't fold the expression, move to the next constant. Note
656 // that this is impossible to happen in practice because we always
657 // constant fold constant ints to constant ints.
658 ++Idx;
659 }
660 }
661
662 // If we are left with a constant zero being added, strip it off.
Reid Spencercae57542007-03-02 00:28:52 +0000663 if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000664 Ops.erase(Ops.begin());
665 --Idx;
666 }
667 }
668
Chris Lattner627018b2004-04-07 16:16:11 +0000669 if (Ops.size() == 1) return Ops[0];
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000670
Chris Lattner53e677a2004-04-02 20:23:17 +0000671 // Okay, check to see if the same value occurs in the operand list twice. If
672 // so, merge them together into an multiply expression. Since we sorted the
673 // list, these values are required to be adjacent.
674 const Type *Ty = Ops[0]->getType();
675 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
676 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
677 // Found a match, merge the two values into a multiply, and add any
678 // remaining values to the result.
Chris Lattnerb06432c2004-04-23 21:29:03 +0000679 SCEVHandle Two = SCEVUnknown::getIntegerSCEV(2, Ty);
Chris Lattner53e677a2004-04-02 20:23:17 +0000680 SCEVHandle Mul = SCEVMulExpr::get(Ops[i], Two);
681 if (Ops.size() == 2)
682 return Mul;
683 Ops.erase(Ops.begin()+i, Ops.begin()+i+2);
684 Ops.push_back(Mul);
685 return SCEVAddExpr::get(Ops);
686 }
687
Dan Gohmanf50cd742007-06-18 19:30:09 +0000688 // Now we know the first non-constant operand. Skip past any cast SCEVs.
689 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
690 ++Idx;
691
692 // If there are add operands they would be next.
Chris Lattner53e677a2004-04-02 20:23:17 +0000693 if (Idx < Ops.size()) {
694 bool DeletedAdd = false;
695 while (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
696 // If we have an add, expand the add operands onto the end of the operands
697 // list.
698 Ops.insert(Ops.end(), Add->op_begin(), Add->op_end());
699 Ops.erase(Ops.begin()+Idx);
700 DeletedAdd = true;
701 }
702
703 // If we deleted at least one add, we added operands to the end of the list,
704 // and they are not necessarily sorted. Recurse to resort and resimplify
705 // any operands we just aquired.
706 if (DeletedAdd)
707 return get(Ops);
708 }
709
710 // Skip over the add expression until we get to a multiply.
711 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
712 ++Idx;
713
714 // If we are adding something to a multiply expression, make sure the
715 // something is not already an operand of the multiply. If so, merge it into
716 // the multiply.
717 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
718 SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
719 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
720 SCEV *MulOpSCEV = Mul->getOperand(MulOp);
721 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
Chris Lattner6a1a78a2004-12-04 20:54:32 +0000722 if (MulOpSCEV == Ops[AddOp] && !isa<SCEVConstant>(MulOpSCEV)) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000723 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
724 SCEVHandle InnerMul = Mul->getOperand(MulOp == 0);
725 if (Mul->getNumOperands() != 2) {
726 // If the multiply has more than two operands, we must get the
727 // Y*Z term.
728 std::vector<SCEVHandle> MulOps(Mul->op_begin(), Mul->op_end());
729 MulOps.erase(MulOps.begin()+MulOp);
730 InnerMul = SCEVMulExpr::get(MulOps);
731 }
Chris Lattnerb06432c2004-04-23 21:29:03 +0000732 SCEVHandle One = SCEVUnknown::getIntegerSCEV(1, Ty);
Chris Lattner53e677a2004-04-02 20:23:17 +0000733 SCEVHandle AddOne = SCEVAddExpr::get(InnerMul, One);
734 SCEVHandle OuterMul = SCEVMulExpr::get(AddOne, Ops[AddOp]);
735 if (Ops.size() == 2) return OuterMul;
736 if (AddOp < Idx) {
737 Ops.erase(Ops.begin()+AddOp);
738 Ops.erase(Ops.begin()+Idx-1);
739 } else {
740 Ops.erase(Ops.begin()+Idx);
741 Ops.erase(Ops.begin()+AddOp-1);
742 }
743 Ops.push_back(OuterMul);
744 return SCEVAddExpr::get(Ops);
745 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000746
Chris Lattner53e677a2004-04-02 20:23:17 +0000747 // Check this multiply against other multiplies being added together.
748 for (unsigned OtherMulIdx = Idx+1;
749 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
750 ++OtherMulIdx) {
751 SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
752 // If MulOp occurs in OtherMul, we can fold the two multiplies
753 // together.
754 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
755 OMulOp != e; ++OMulOp)
756 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
757 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
758 SCEVHandle InnerMul1 = Mul->getOperand(MulOp == 0);
759 if (Mul->getNumOperands() != 2) {
760 std::vector<SCEVHandle> MulOps(Mul->op_begin(), Mul->op_end());
761 MulOps.erase(MulOps.begin()+MulOp);
762 InnerMul1 = SCEVMulExpr::get(MulOps);
763 }
764 SCEVHandle InnerMul2 = OtherMul->getOperand(OMulOp == 0);
765 if (OtherMul->getNumOperands() != 2) {
766 std::vector<SCEVHandle> MulOps(OtherMul->op_begin(),
767 OtherMul->op_end());
768 MulOps.erase(MulOps.begin()+OMulOp);
769 InnerMul2 = SCEVMulExpr::get(MulOps);
770 }
771 SCEVHandle InnerMulSum = SCEVAddExpr::get(InnerMul1,InnerMul2);
772 SCEVHandle OuterMul = SCEVMulExpr::get(MulOpSCEV, InnerMulSum);
773 if (Ops.size() == 2) return OuterMul;
774 Ops.erase(Ops.begin()+Idx);
775 Ops.erase(Ops.begin()+OtherMulIdx-1);
776 Ops.push_back(OuterMul);
777 return SCEVAddExpr::get(Ops);
778 }
779 }
780 }
781 }
782
783 // If there are any add recurrences in the operands list, see if any other
784 // added values are loop invariant. If so, we can fold them into the
785 // recurrence.
786 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
787 ++Idx;
788
789 // Scan over all recurrences, trying to fold loop invariants into them.
790 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
791 // Scan all of the other operands to this add and add them to the vector if
792 // they are loop invariant w.r.t. the recurrence.
793 std::vector<SCEVHandle> LIOps;
794 SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
795 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
796 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
797 LIOps.push_back(Ops[i]);
798 Ops.erase(Ops.begin()+i);
799 --i; --e;
800 }
801
802 // If we found some loop invariants, fold them into the recurrence.
803 if (!LIOps.empty()) {
804 // NLI + LI + { Start,+,Step} --> NLI + { LI+Start,+,Step }
805 LIOps.push_back(AddRec->getStart());
806
807 std::vector<SCEVHandle> AddRecOps(AddRec->op_begin(), AddRec->op_end());
808 AddRecOps[0] = SCEVAddExpr::get(LIOps);
809
810 SCEVHandle NewRec = SCEVAddRecExpr::get(AddRecOps, AddRec->getLoop());
811 // If all of the other operands were loop invariant, we are done.
812 if (Ops.size() == 1) return NewRec;
813
814 // Otherwise, add the folded AddRec by the non-liv parts.
815 for (unsigned i = 0;; ++i)
816 if (Ops[i] == AddRec) {
817 Ops[i] = NewRec;
818 break;
819 }
820 return SCEVAddExpr::get(Ops);
821 }
822
823 // Okay, if there weren't any loop invariants to be folded, check to see if
824 // there are multiple AddRec's with the same loop induction variable being
825 // added together. If so, we can fold them.
826 for (unsigned OtherIdx = Idx+1;
827 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
828 if (OtherIdx != Idx) {
829 SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
830 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
831 // Other + {A,+,B} + {C,+,D} --> Other + {A+C,+,B+D}
832 std::vector<SCEVHandle> NewOps(AddRec->op_begin(), AddRec->op_end());
833 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); i != e; ++i) {
834 if (i >= NewOps.size()) {
835 NewOps.insert(NewOps.end(), OtherAddRec->op_begin()+i,
836 OtherAddRec->op_end());
837 break;
838 }
839 NewOps[i] = SCEVAddExpr::get(NewOps[i], OtherAddRec->getOperand(i));
840 }
841 SCEVHandle NewAddRec = SCEVAddRecExpr::get(NewOps, AddRec->getLoop());
842
843 if (Ops.size() == 2) return NewAddRec;
844
845 Ops.erase(Ops.begin()+Idx);
846 Ops.erase(Ops.begin()+OtherIdx-1);
847 Ops.push_back(NewAddRec);
848 return SCEVAddExpr::get(Ops);
849 }
850 }
851
852 // Otherwise couldn't fold anything into this recurrence. Move onto the
853 // next one.
854 }
855
856 // Okay, it looks like we really DO need an add expr. Check to see if we
857 // already have one, otherwise create a new one.
858 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
Chris Lattnerb3364092006-10-04 21:49:37 +0000859 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scAddExpr,
860 SCEVOps)];
Chris Lattner53e677a2004-04-02 20:23:17 +0000861 if (Result == 0) Result = new SCEVAddExpr(Ops);
862 return Result;
863}
864
865
866SCEVHandle SCEVMulExpr::get(std::vector<SCEVHandle> &Ops) {
867 assert(!Ops.empty() && "Cannot get empty mul!");
868
869 // Sort by complexity, this groups all similar expression types together.
Chris Lattner8d741b82004-06-20 06:23:15 +0000870 GroupByComplexity(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +0000871
872 // If there are any constants, fold them together.
873 unsigned Idx = 0;
874 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
875
876 // C1*(C2+V) -> C1*C2 + C1*V
877 if (Ops.size() == 2)
878 if (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
879 if (Add->getNumOperands() == 2 &&
880 isa<SCEVConstant>(Add->getOperand(0)))
881 return SCEVAddExpr::get(SCEVMulExpr::get(LHSC, Add->getOperand(0)),
882 SCEVMulExpr::get(LHSC, Add->getOperand(1)));
883
884
885 ++Idx;
886 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
887 // We found two constants, fold them together!
Zhou Shengfdc1e162007-04-07 17:40:57 +0000888 Constant *Fold = ConstantInt::get(LHSC->getValue()->getValue() *
889 RHSC->getValue()->getValue());
Chris Lattner53e677a2004-04-02 20:23:17 +0000890 if (ConstantInt *CI = dyn_cast<ConstantInt>(Fold)) {
891 Ops[0] = SCEVConstant::get(CI);
892 Ops.erase(Ops.begin()+1); // Erase the folded element
893 if (Ops.size() == 1) return Ops[0];
Chris Lattner7ffc07d2005-02-26 18:50:19 +0000894 LHSC = cast<SCEVConstant>(Ops[0]);
Chris Lattner53e677a2004-04-02 20:23:17 +0000895 } else {
896 // If we couldn't fold the expression, move to the next constant. Note
897 // that this is impossible to happen in practice because we always
898 // constant fold constant ints to constant ints.
899 ++Idx;
900 }
901 }
902
903 // If we are left with a constant one being multiplied, strip it off.
904 if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) {
905 Ops.erase(Ops.begin());
906 --Idx;
Reid Spencercae57542007-03-02 00:28:52 +0000907 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000908 // If we have a multiply of zero, it will always be zero.
909 return Ops[0];
910 }
911 }
912
913 // Skip over the add expression until we get to a multiply.
914 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
915 ++Idx;
916
917 if (Ops.size() == 1)
918 return Ops[0];
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000919
Chris Lattner53e677a2004-04-02 20:23:17 +0000920 // If there are mul operands inline them all into this expression.
921 if (Idx < Ops.size()) {
922 bool DeletedMul = false;
923 while (SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
924 // If we have an mul, expand the mul operands onto the end of the operands
925 // list.
926 Ops.insert(Ops.end(), Mul->op_begin(), Mul->op_end());
927 Ops.erase(Ops.begin()+Idx);
928 DeletedMul = true;
929 }
930
931 // If we deleted at least one mul, we added operands to the end of the list,
932 // and they are not necessarily sorted. Recurse to resort and resimplify
933 // any operands we just aquired.
934 if (DeletedMul)
935 return get(Ops);
936 }
937
938 // If there are any add recurrences in the operands list, see if any other
939 // added values are loop invariant. If so, we can fold them into the
940 // recurrence.
941 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
942 ++Idx;
943
944 // Scan over all recurrences, trying to fold loop invariants into them.
945 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
946 // Scan all of the other operands to this mul and add them to the vector if
947 // they are loop invariant w.r.t. the recurrence.
948 std::vector<SCEVHandle> LIOps;
949 SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
950 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
951 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
952 LIOps.push_back(Ops[i]);
953 Ops.erase(Ops.begin()+i);
954 --i; --e;
955 }
956
957 // If we found some loop invariants, fold them into the recurrence.
958 if (!LIOps.empty()) {
959 // NLI * LI * { Start,+,Step} --> NLI * { LI*Start,+,LI*Step }
960 std::vector<SCEVHandle> NewOps;
961 NewOps.reserve(AddRec->getNumOperands());
962 if (LIOps.size() == 1) {
963 SCEV *Scale = LIOps[0];
964 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
965 NewOps.push_back(SCEVMulExpr::get(Scale, AddRec->getOperand(i)));
966 } else {
967 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
968 std::vector<SCEVHandle> MulOps(LIOps);
969 MulOps.push_back(AddRec->getOperand(i));
970 NewOps.push_back(SCEVMulExpr::get(MulOps));
971 }
972 }
973
974 SCEVHandle NewRec = SCEVAddRecExpr::get(NewOps, AddRec->getLoop());
975
976 // If all of the other operands were loop invariant, we are done.
977 if (Ops.size() == 1) return NewRec;
978
979 // Otherwise, multiply the folded AddRec by the non-liv parts.
980 for (unsigned i = 0;; ++i)
981 if (Ops[i] == AddRec) {
982 Ops[i] = NewRec;
983 break;
984 }
985 return SCEVMulExpr::get(Ops);
986 }
987
988 // Okay, if there weren't any loop invariants to be folded, check to see if
989 // there are multiple AddRec's with the same loop induction variable being
990 // multiplied together. If so, we can fold them.
991 for (unsigned OtherIdx = Idx+1;
992 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
993 if (OtherIdx != Idx) {
994 SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
995 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
996 // F * G --> {A,+,B} * {C,+,D} --> {A*C,+,F*D + G*B + B*D}
997 SCEVAddRecExpr *F = AddRec, *G = OtherAddRec;
998 SCEVHandle NewStart = SCEVMulExpr::get(F->getStart(),
999 G->getStart());
1000 SCEVHandle B = F->getStepRecurrence();
1001 SCEVHandle D = G->getStepRecurrence();
1002 SCEVHandle NewStep = SCEVAddExpr::get(SCEVMulExpr::get(F, D),
1003 SCEVMulExpr::get(G, B),
1004 SCEVMulExpr::get(B, D));
1005 SCEVHandle NewAddRec = SCEVAddRecExpr::get(NewStart, NewStep,
1006 F->getLoop());
1007 if (Ops.size() == 2) return NewAddRec;
1008
1009 Ops.erase(Ops.begin()+Idx);
1010 Ops.erase(Ops.begin()+OtherIdx-1);
1011 Ops.push_back(NewAddRec);
1012 return SCEVMulExpr::get(Ops);
1013 }
1014 }
1015
1016 // Otherwise couldn't fold anything into this recurrence. Move onto the
1017 // next one.
1018 }
1019
1020 // Okay, it looks like we really DO need an mul expr. Check to see if we
1021 // already have one, otherwise create a new one.
1022 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
Chris Lattnerb3364092006-10-04 21:49:37 +00001023 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scMulExpr,
1024 SCEVOps)];
Chris Lattner6a1a78a2004-12-04 20:54:32 +00001025 if (Result == 0)
1026 Result = new SCEVMulExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +00001027 return Result;
1028}
1029
Chris Lattner60a05cc2006-04-01 04:48:52 +00001030SCEVHandle SCEVSDivExpr::get(const SCEVHandle &LHS, const SCEVHandle &RHS) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001031 if (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
1032 if (RHSC->getValue()->equalsInt(1))
Reid Spencer1628cec2006-10-26 06:15:43 +00001033 return LHS; // X sdiv 1 --> x
Chris Lattner53e677a2004-04-02 20:23:17 +00001034 if (RHSC->getValue()->isAllOnesValue())
Reid Spencer1628cec2006-10-26 06:15:43 +00001035 return SCEV::getNegativeSCEV(LHS); // X sdiv -1 --> -x
Chris Lattner53e677a2004-04-02 20:23:17 +00001036
1037 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
1038 Constant *LHSCV = LHSC->getValue();
1039 Constant *RHSCV = RHSC->getValue();
Reid Spencer1628cec2006-10-26 06:15:43 +00001040 return SCEVUnknown::get(ConstantExpr::getSDiv(LHSCV, RHSCV));
Chris Lattner53e677a2004-04-02 20:23:17 +00001041 }
1042 }
1043
1044 // FIXME: implement folding of (X*4)/4 when we know X*4 doesn't overflow.
1045
Chris Lattnerb3364092006-10-04 21:49:37 +00001046 SCEVSDivExpr *&Result = (*SCEVSDivs)[std::make_pair(LHS, RHS)];
Chris Lattner60a05cc2006-04-01 04:48:52 +00001047 if (Result == 0) Result = new SCEVSDivExpr(LHS, RHS);
Chris Lattner53e677a2004-04-02 20:23:17 +00001048 return Result;
1049}
1050
1051
1052/// SCEVAddRecExpr::get - Get a add recurrence expression for the
1053/// specified loop. Simplify the expression as much as possible.
1054SCEVHandle SCEVAddRecExpr::get(const SCEVHandle &Start,
1055 const SCEVHandle &Step, const Loop *L) {
1056 std::vector<SCEVHandle> Operands;
1057 Operands.push_back(Start);
1058 if (SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
1059 if (StepChrec->getLoop() == L) {
1060 Operands.insert(Operands.end(), StepChrec->op_begin(),
1061 StepChrec->op_end());
1062 return get(Operands, L);
1063 }
1064
1065 Operands.push_back(Step);
1066 return get(Operands, L);
1067}
1068
1069/// SCEVAddRecExpr::get - Get a add recurrence expression for the
1070/// specified loop. Simplify the expression as much as possible.
1071SCEVHandle SCEVAddRecExpr::get(std::vector<SCEVHandle> &Operands,
1072 const Loop *L) {
1073 if (Operands.size() == 1) return Operands[0];
1074
1075 if (SCEVConstant *StepC = dyn_cast<SCEVConstant>(Operands.back()))
Reid Spencercae57542007-03-02 00:28:52 +00001076 if (StepC->getValue()->isZero()) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001077 Operands.pop_back();
1078 return get(Operands, L); // { X,+,0 } --> X
1079 }
1080
1081 SCEVAddRecExpr *&Result =
Chris Lattnerb3364092006-10-04 21:49:37 +00001082 (*SCEVAddRecExprs)[std::make_pair(L, std::vector<SCEV*>(Operands.begin(),
1083 Operands.end()))];
Chris Lattner53e677a2004-04-02 20:23:17 +00001084 if (Result == 0) Result = new SCEVAddRecExpr(Operands, L);
1085 return Result;
1086}
1087
Chris Lattner0a7f98c2004-04-15 15:07:24 +00001088SCEVHandle SCEVUnknown::get(Value *V) {
1089 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
1090 return SCEVConstant::get(CI);
Chris Lattnerb3364092006-10-04 21:49:37 +00001091 SCEVUnknown *&Result = (*SCEVUnknowns)[V];
Chris Lattner0a7f98c2004-04-15 15:07:24 +00001092 if (Result == 0) Result = new SCEVUnknown(V);
1093 return Result;
1094}
1095
Chris Lattner53e677a2004-04-02 20:23:17 +00001096
1097//===----------------------------------------------------------------------===//
Chris Lattner53e677a2004-04-02 20:23:17 +00001098// ScalarEvolutionsImpl Definition and Implementation
1099//===----------------------------------------------------------------------===//
1100//
1101/// ScalarEvolutionsImpl - This class implements the main driver for the scalar
1102/// evolution code.
1103///
1104namespace {
Chris Lattner95255282006-06-28 23:17:24 +00001105 struct VISIBILITY_HIDDEN ScalarEvolutionsImpl {
Chris Lattner53e677a2004-04-02 20:23:17 +00001106 /// F - The function we are analyzing.
1107 ///
1108 Function &F;
1109
1110 /// LI - The loop information for the function we are currently analyzing.
1111 ///
1112 LoopInfo &LI;
1113
1114 /// UnknownValue - This SCEV is used to represent unknown trip counts and
1115 /// things.
1116 SCEVHandle UnknownValue;
1117
1118 /// Scalars - This is a cache of the scalars we have analyzed so far.
1119 ///
1120 std::map<Value*, SCEVHandle> Scalars;
1121
1122 /// IterationCounts - Cache the iteration count of the loops for this
1123 /// function as they are computed.
1124 std::map<const Loop*, SCEVHandle> IterationCounts;
1125
Chris Lattner3221ad02004-04-17 22:58:41 +00001126 /// ConstantEvolutionLoopExitValue - This map contains entries for all of
1127 /// the PHI instructions that we attempt to compute constant evolutions for.
1128 /// This allows us to avoid potentially expensive recomputation of these
1129 /// properties. An instruction maps to null if we are unable to compute its
1130 /// exit value.
1131 std::map<PHINode*, Constant*> ConstantEvolutionLoopExitValue;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001132
Chris Lattner53e677a2004-04-02 20:23:17 +00001133 public:
1134 ScalarEvolutionsImpl(Function &f, LoopInfo &li)
1135 : F(f), LI(li), UnknownValue(new SCEVCouldNotCompute()) {}
1136
1137 /// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
1138 /// expression and create a new one.
1139 SCEVHandle getSCEV(Value *V);
1140
Chris Lattnera0740fb2005-08-09 23:36:33 +00001141 /// hasSCEV - Return true if the SCEV for this value has already been
1142 /// computed.
1143 bool hasSCEV(Value *V) const {
1144 return Scalars.count(V);
1145 }
1146
1147 /// setSCEV - Insert the specified SCEV into the map of current SCEVs for
1148 /// the specified value.
1149 void setSCEV(Value *V, const SCEVHandle &H) {
1150 bool isNew = Scalars.insert(std::make_pair(V, H)).second;
1151 assert(isNew && "This entry already existed!");
1152 }
1153
1154
Chris Lattner53e677a2004-04-02 20:23:17 +00001155 /// getSCEVAtScope - Compute the value of the specified expression within
1156 /// the indicated loop (which may be null to indicate in no loop). If the
1157 /// expression cannot be evaluated, return UnknownValue itself.
1158 SCEVHandle getSCEVAtScope(SCEV *V, const Loop *L);
1159
1160
1161 /// hasLoopInvariantIterationCount - Return true if the specified loop has
1162 /// an analyzable loop-invariant iteration count.
1163 bool hasLoopInvariantIterationCount(const Loop *L);
1164
1165 /// getIterationCount - If the specified loop has a predictable iteration
1166 /// count, return it. Note that it is not valid to call this method on a
1167 /// loop without a loop-invariant iteration count.
1168 SCEVHandle getIterationCount(const Loop *L);
1169
Dan Gohman5cec4db2007-06-19 14:28:31 +00001170 /// deleteValueFromRecords - This method should be called by the
1171 /// client before it removes a value from the program, to make sure
Chris Lattner53e677a2004-04-02 20:23:17 +00001172 /// that no dangling references are left around.
Dan Gohman5cec4db2007-06-19 14:28:31 +00001173 void deleteValueFromRecords(Value *V);
Chris Lattner53e677a2004-04-02 20:23:17 +00001174
1175 private:
1176 /// createSCEV - We know that there is no SCEV for the specified value.
1177 /// Analyze the expression.
1178 SCEVHandle createSCEV(Value *V);
Chris Lattner53e677a2004-04-02 20:23:17 +00001179
1180 /// createNodeForPHI - Provide the special handling we need to analyze PHI
1181 /// SCEVs.
1182 SCEVHandle createNodeForPHI(PHINode *PN);
Chris Lattner4dc534c2005-02-13 04:37:18 +00001183
1184 /// ReplaceSymbolicValueWithConcrete - This looks up the computed SCEV value
1185 /// for the specified instruction and replaces any references to the
1186 /// symbolic value SymName with the specified value. This is used during
1187 /// PHI resolution.
1188 void ReplaceSymbolicValueWithConcrete(Instruction *I,
1189 const SCEVHandle &SymName,
1190 const SCEVHandle &NewVal);
Chris Lattner53e677a2004-04-02 20:23:17 +00001191
1192 /// ComputeIterationCount - Compute the number of times the specified loop
1193 /// will iterate.
1194 SCEVHandle ComputeIterationCount(const Loop *L);
1195
Chris Lattner673e02b2004-10-12 01:49:27 +00001196 /// ComputeLoadConstantCompareIterationCount - Given an exit condition of
Zhou Sheng83428362007-04-07 17:12:38 +00001197 /// 'setcc load X, cst', try to see if we can compute the trip count.
Chris Lattner673e02b2004-10-12 01:49:27 +00001198 SCEVHandle ComputeLoadConstantCompareIterationCount(LoadInst *LI,
1199 Constant *RHS,
1200 const Loop *L,
Reid Spencere4d87aa2006-12-23 06:05:41 +00001201 ICmpInst::Predicate p);
Chris Lattner673e02b2004-10-12 01:49:27 +00001202
Chris Lattner7980fb92004-04-17 18:36:24 +00001203 /// ComputeIterationCountExhaustively - If the trip is known to execute a
1204 /// constant number of times (the condition evolves only from constants),
1205 /// try to evaluate a few iterations of the loop until we get the exit
1206 /// condition gets a value of ExitWhen (true or false). If we cannot
1207 /// evaluate the trip count of the loop, return UnknownValue.
1208 SCEVHandle ComputeIterationCountExhaustively(const Loop *L, Value *Cond,
1209 bool ExitWhen);
1210
Chris Lattner53e677a2004-04-02 20:23:17 +00001211 /// HowFarToZero - Return the number of times a backedge comparing the
1212 /// specified value to zero will execute. If not computable, return
Chris Lattnerdb25de42005-08-15 23:33:51 +00001213 /// UnknownValue.
Chris Lattner53e677a2004-04-02 20:23:17 +00001214 SCEVHandle HowFarToZero(SCEV *V, const Loop *L);
1215
1216 /// HowFarToNonZero - Return the number of times a backedge checking the
1217 /// specified value for nonzero will execute. If not computable, return
Chris Lattnerdb25de42005-08-15 23:33:51 +00001218 /// UnknownValue.
Chris Lattner53e677a2004-04-02 20:23:17 +00001219 SCEVHandle HowFarToNonZero(SCEV *V, const Loop *L);
Chris Lattner3221ad02004-04-17 22:58:41 +00001220
Chris Lattnerdb25de42005-08-15 23:33:51 +00001221 /// HowManyLessThans - Return the number of times a backedge containing the
1222 /// specified less-than comparison will execute. If not computable, return
Nick Lewyckyd6dac0e2007-08-06 19:21:00 +00001223 /// UnknownValue. isSigned specifies whether the less-than is signed.
1224 SCEVHandle HowManyLessThans(SCEV *LHS, SCEV *RHS, const Loop *L,
1225 bool isSigned);
Chris Lattnerdb25de42005-08-15 23:33:51 +00001226
Chris Lattner3221ad02004-04-17 22:58:41 +00001227 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
1228 /// in the header of its containing loop, we know the loop executes a
1229 /// constant number of times, and the PHI node is just a recurrence
1230 /// involving constants, fold it.
Reid Spencere8019bb2007-03-01 07:25:48 +00001231 Constant *getConstantEvolutionLoopExitValue(PHINode *PN, const APInt& Its,
Chris Lattner3221ad02004-04-17 22:58:41 +00001232 const Loop *L);
Chris Lattner53e677a2004-04-02 20:23:17 +00001233 };
1234}
1235
1236//===----------------------------------------------------------------------===//
1237// Basic SCEV Analysis and PHI Idiom Recognition Code
1238//
1239
Dan Gohman5cec4db2007-06-19 14:28:31 +00001240/// deleteValueFromRecords - This method should be called by the
Chris Lattner53e677a2004-04-02 20:23:17 +00001241/// client before it removes an instruction from the program, to make sure
1242/// that no dangling references are left around.
Dan Gohman5cec4db2007-06-19 14:28:31 +00001243void ScalarEvolutionsImpl::deleteValueFromRecords(Value *V) {
1244 SmallVector<Value *, 16> Worklist;
Nick Lewycky9d0332f2007-06-06 04:12:20 +00001245
Dan Gohman5cec4db2007-06-19 14:28:31 +00001246 if (Scalars.erase(V)) {
1247 if (PHINode *PN = dyn_cast<PHINode>(V))
Nick Lewycky9d0332f2007-06-06 04:12:20 +00001248 ConstantEvolutionLoopExitValue.erase(PN);
Dan Gohman5cec4db2007-06-19 14:28:31 +00001249 Worklist.push_back(V);
Nick Lewycky9d0332f2007-06-06 04:12:20 +00001250 }
1251
1252 while (!Worklist.empty()) {
Dan Gohman5cec4db2007-06-19 14:28:31 +00001253 Value *VV = Worklist.back();
Nick Lewycky9d0332f2007-06-06 04:12:20 +00001254 Worklist.pop_back();
1255
Dan Gohman5cec4db2007-06-19 14:28:31 +00001256 for (Instruction::use_iterator UI = VV->use_begin(), UE = VV->use_end();
Nick Lewycky9d0332f2007-06-06 04:12:20 +00001257 UI != UE; ++UI) {
Nick Lewycky51e844b2007-06-06 11:26:20 +00001258 Instruction *Inst = cast<Instruction>(*UI);
1259 if (Scalars.erase(Inst)) {
Dan Gohman5cec4db2007-06-19 14:28:31 +00001260 if (PHINode *PN = dyn_cast<PHINode>(VV))
Nick Lewycky9d0332f2007-06-06 04:12:20 +00001261 ConstantEvolutionLoopExitValue.erase(PN);
1262 Worklist.push_back(Inst);
1263 }
1264 }
1265 }
Chris Lattner53e677a2004-04-02 20:23:17 +00001266}
1267
1268
1269/// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
1270/// expression and create a new one.
1271SCEVHandle ScalarEvolutionsImpl::getSCEV(Value *V) {
1272 assert(V->getType() != Type::VoidTy && "Can't analyze void expressions!");
1273
1274 std::map<Value*, SCEVHandle>::iterator I = Scalars.find(V);
1275 if (I != Scalars.end()) return I->second;
1276 SCEVHandle S = createSCEV(V);
1277 Scalars.insert(std::make_pair(V, S));
1278 return S;
1279}
1280
Chris Lattner4dc534c2005-02-13 04:37:18 +00001281/// ReplaceSymbolicValueWithConcrete - This looks up the computed SCEV value for
1282/// the specified instruction and replaces any references to the symbolic value
1283/// SymName with the specified value. This is used during PHI resolution.
1284void ScalarEvolutionsImpl::
1285ReplaceSymbolicValueWithConcrete(Instruction *I, const SCEVHandle &SymName,
1286 const SCEVHandle &NewVal) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001287 std::map<Value*, SCEVHandle>::iterator SI = Scalars.find(I);
Chris Lattner4dc534c2005-02-13 04:37:18 +00001288 if (SI == Scalars.end()) return;
Chris Lattner53e677a2004-04-02 20:23:17 +00001289
Chris Lattner4dc534c2005-02-13 04:37:18 +00001290 SCEVHandle NV =
1291 SI->second->replaceSymbolicValuesWithConcrete(SymName, NewVal);
1292 if (NV == SI->second) return; // No change.
1293
1294 SI->second = NV; // Update the scalars map!
1295
1296 // Any instruction values that use this instruction might also need to be
1297 // updated!
1298 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1299 UI != E; ++UI)
1300 ReplaceSymbolicValueWithConcrete(cast<Instruction>(*UI), SymName, NewVal);
1301}
Chris Lattner53e677a2004-04-02 20:23:17 +00001302
1303/// createNodeForPHI - PHI nodes have two cases. Either the PHI node exists in
1304/// a loop header, making it a potential recurrence, or it doesn't.
1305///
1306SCEVHandle ScalarEvolutionsImpl::createNodeForPHI(PHINode *PN) {
1307 if (PN->getNumIncomingValues() == 2) // The loops have been canonicalized.
1308 if (const Loop *L = LI.getLoopFor(PN->getParent()))
1309 if (L->getHeader() == PN->getParent()) {
1310 // If it lives in the loop header, it has two incoming values, one
1311 // from outside the loop, and one from inside.
1312 unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0));
1313 unsigned BackEdge = IncomingEdge^1;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001314
Chris Lattner53e677a2004-04-02 20:23:17 +00001315 // While we are analyzing this PHI node, handle its value symbolically.
1316 SCEVHandle SymbolicName = SCEVUnknown::get(PN);
1317 assert(Scalars.find(PN) == Scalars.end() &&
1318 "PHI node already processed?");
1319 Scalars.insert(std::make_pair(PN, SymbolicName));
1320
1321 // Using this symbolic name for the PHI, analyze the value coming around
1322 // the back-edge.
1323 SCEVHandle BEValue = getSCEV(PN->getIncomingValue(BackEdge));
1324
1325 // NOTE: If BEValue is loop invariant, we know that the PHI node just
1326 // has a special value for the first iteration of the loop.
1327
1328 // If the value coming around the backedge is an add with the symbolic
1329 // value we just inserted, then we found a simple induction variable!
1330 if (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
1331 // If there is a single occurrence of the symbolic value, replace it
1332 // with a recurrence.
1333 unsigned FoundIndex = Add->getNumOperands();
1334 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
1335 if (Add->getOperand(i) == SymbolicName)
1336 if (FoundIndex == e) {
1337 FoundIndex = i;
1338 break;
1339 }
1340
1341 if (FoundIndex != Add->getNumOperands()) {
1342 // Create an add with everything but the specified operand.
1343 std::vector<SCEVHandle> Ops;
1344 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
1345 if (i != FoundIndex)
1346 Ops.push_back(Add->getOperand(i));
1347 SCEVHandle Accum = SCEVAddExpr::get(Ops);
1348
1349 // This is not a valid addrec if the step amount is varying each
1350 // loop iteration, but is not itself an addrec in this loop.
1351 if (Accum->isLoopInvariant(L) ||
1352 (isa<SCEVAddRecExpr>(Accum) &&
1353 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
1354 SCEVHandle StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
1355 SCEVHandle PHISCEV = SCEVAddRecExpr::get(StartVal, Accum, L);
1356
1357 // Okay, for the entire analysis of this edge we assumed the PHI
1358 // to be symbolic. We now need to go back and update all of the
1359 // entries for the scalars that use the PHI (except for the PHI
1360 // itself) to use the new analyzed value instead of the "symbolic"
1361 // value.
Chris Lattner4dc534c2005-02-13 04:37:18 +00001362 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
Chris Lattner53e677a2004-04-02 20:23:17 +00001363 return PHISCEV;
1364 }
1365 }
Chris Lattner97156e72006-04-26 18:34:07 +00001366 } else if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(BEValue)) {
1367 // Otherwise, this could be a loop like this:
1368 // i = 0; for (j = 1; ..; ++j) { .... i = j; }
1369 // In this case, j = {1,+,1} and BEValue is j.
1370 // Because the other in-value of i (0) fits the evolution of BEValue
1371 // i really is an addrec evolution.
1372 if (AddRec->getLoop() == L && AddRec->isAffine()) {
1373 SCEVHandle StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
1374
1375 // If StartVal = j.start - j.stride, we can use StartVal as the
1376 // initial step of the addrec evolution.
1377 if (StartVal == SCEV::getMinusSCEV(AddRec->getOperand(0),
1378 AddRec->getOperand(1))) {
1379 SCEVHandle PHISCEV =
1380 SCEVAddRecExpr::get(StartVal, AddRec->getOperand(1), L);
1381
1382 // Okay, for the entire analysis of this edge we assumed the PHI
1383 // to be symbolic. We now need to go back and update all of the
1384 // entries for the scalars that use the PHI (except for the PHI
1385 // itself) to use the new analyzed value instead of the "symbolic"
1386 // value.
1387 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
1388 return PHISCEV;
1389 }
1390 }
Chris Lattner53e677a2004-04-02 20:23:17 +00001391 }
1392
1393 return SymbolicName;
1394 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001395
Chris Lattner53e677a2004-04-02 20:23:17 +00001396 // If it's not a loop phi, we can't handle it yet.
1397 return SCEVUnknown::get(PN);
1398}
1399
Chris Lattnera17f0392006-12-12 02:26:09 +00001400/// GetConstantFactor - Determine the largest constant factor that S has. For
1401/// example, turn {4,+,8} -> 4. (S umod result) should always equal zero.
Reid Spencer6263cba2007-02-28 23:31:17 +00001402static APInt GetConstantFactor(SCEVHandle S) {
Chris Lattnera17f0392006-12-12 02:26:09 +00001403 if (SCEVConstant *C = dyn_cast<SCEVConstant>(S)) {
Zhou Sheng414de4d2007-04-07 17:48:27 +00001404 const APInt& V = C->getValue()->getValue();
Reid Spencer6263cba2007-02-28 23:31:17 +00001405 if (!V.isMinValue())
Chris Lattnera17f0392006-12-12 02:26:09 +00001406 return V;
1407 else // Zero is a multiple of everything.
Reid Spencer6263cba2007-02-28 23:31:17 +00001408 return APInt(C->getBitWidth(), 1).shl(C->getBitWidth()-1);
Chris Lattnera17f0392006-12-12 02:26:09 +00001409 }
1410
Reid Spencer9b4aeb32007-03-02 02:59:25 +00001411 if (SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S)) {
Zhou Sheng83428362007-04-07 17:12:38 +00001412 return GetConstantFactor(T->getOperand()).trunc(
1413 cast<IntegerType>(T->getType())->getBitWidth());
Reid Spencer9b4aeb32007-03-02 02:59:25 +00001414 }
Chris Lattnera17f0392006-12-12 02:26:09 +00001415 if (SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S))
Zhou Sheng83428362007-04-07 17:12:38 +00001416 return GetConstantFactor(E->getOperand()).zext(
1417 cast<IntegerType>(E->getType())->getBitWidth());
Dan Gohmand19534a2007-06-15 14:38:12 +00001418 if (SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S))
1419 return GetConstantFactor(E->getOperand()).sext(
1420 cast<IntegerType>(E->getType())->getBitWidth());
Chris Lattnera17f0392006-12-12 02:26:09 +00001421
1422 if (SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
1423 // The result is the min of all operands.
Zhou Sheng83428362007-04-07 17:12:38 +00001424 APInt Res(GetConstantFactor(A->getOperand(0)));
Reid Spencer6263cba2007-02-28 23:31:17 +00001425 for (unsigned i = 1, e = A->getNumOperands();
Reid Spencer07976052007-03-04 01:25:35 +00001426 i != e && Res.ugt(APInt(Res.getBitWidth(),1)); ++i) {
1427 APInt Tmp(GetConstantFactor(A->getOperand(i)));
Reid Spencer07976052007-03-04 01:25:35 +00001428 Res = APIntOps::umin(Res, Tmp);
1429 }
Chris Lattnera17f0392006-12-12 02:26:09 +00001430 return Res;
1431 }
1432
1433 if (SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
1434 // The result is the product of all the operands.
Zhou Sheng83428362007-04-07 17:12:38 +00001435 APInt Res(GetConstantFactor(M->getOperand(0)));
Reid Spencer07976052007-03-04 01:25:35 +00001436 for (unsigned i = 1, e = M->getNumOperands(); i != e; ++i) {
1437 APInt Tmp(GetConstantFactor(M->getOperand(i)));
Reid Spencer07976052007-03-04 01:25:35 +00001438 Res *= Tmp;
1439 }
Chris Lattnera17f0392006-12-12 02:26:09 +00001440 return Res;
1441 }
1442
1443 if (SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
Chris Lattner75de5ab2006-12-19 01:16:02 +00001444 // For now, we just handle linear expressions.
1445 if (A->getNumOperands() == 2) {
1446 // We want the GCD between the start and the stride value.
Zhou Sheng83428362007-04-07 17:12:38 +00001447 APInt Start(GetConstantFactor(A->getOperand(0)));
Reid Spencer6263cba2007-02-28 23:31:17 +00001448 if (Start == 1)
Zhou Sheng83428362007-04-07 17:12:38 +00001449 return Start;
1450 APInt Stride(GetConstantFactor(A->getOperand(1)));
Reid Spencer6263cba2007-02-28 23:31:17 +00001451 return APIntOps::GreatestCommonDivisor(Start, Stride);
Chris Lattner75de5ab2006-12-19 01:16:02 +00001452 }
Chris Lattnera17f0392006-12-12 02:26:09 +00001453 }
1454
1455 // SCEVSDivExpr, SCEVUnknown.
Reid Spencer6263cba2007-02-28 23:31:17 +00001456 return APInt(S->getBitWidth(), 1);
Chris Lattnera17f0392006-12-12 02:26:09 +00001457}
Chris Lattner53e677a2004-04-02 20:23:17 +00001458
1459/// createSCEV - We know that there is no SCEV for the specified value.
1460/// Analyze the expression.
1461///
1462SCEVHandle ScalarEvolutionsImpl::createSCEV(Value *V) {
1463 if (Instruction *I = dyn_cast<Instruction>(V)) {
1464 switch (I->getOpcode()) {
1465 case Instruction::Add:
1466 return SCEVAddExpr::get(getSCEV(I->getOperand(0)),
1467 getSCEV(I->getOperand(1)));
1468 case Instruction::Mul:
1469 return SCEVMulExpr::get(getSCEV(I->getOperand(0)),
1470 getSCEV(I->getOperand(1)));
Reid Spencer1628cec2006-10-26 06:15:43 +00001471 case Instruction::SDiv:
1472 return SCEVSDivExpr::get(getSCEV(I->getOperand(0)),
1473 getSCEV(I->getOperand(1)));
Chris Lattner53e677a2004-04-02 20:23:17 +00001474 break;
1475
1476 case Instruction::Sub:
Chris Lattnerbac5b462005-03-09 05:34:41 +00001477 return SCEV::getMinusSCEV(getSCEV(I->getOperand(0)),
1478 getSCEV(I->getOperand(1)));
Chris Lattnera17f0392006-12-12 02:26:09 +00001479 case Instruction::Or:
1480 // If the RHS of the Or is a constant, we may have something like:
1481 // X*4+1 which got turned into X*4|1. Handle this as an add so loop
1482 // optimizations will transparently handle this case.
1483 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
1484 SCEVHandle LHS = getSCEV(I->getOperand(0));
Zhou Shengfdc1e162007-04-07 17:40:57 +00001485 APInt CommonFact(GetConstantFactor(LHS));
Reid Spencer6263cba2007-02-28 23:31:17 +00001486 assert(!CommonFact.isMinValue() &&
1487 "Common factor should at least be 1!");
1488 if (CommonFact.ugt(CI->getValue())) {
Chris Lattnera17f0392006-12-12 02:26:09 +00001489 // If the LHS is a multiple that is larger than the RHS, use +.
1490 return SCEVAddExpr::get(LHS,
1491 getSCEV(I->getOperand(1)));
1492 }
1493 }
1494 break;
Chris Lattner2811f2a2007-04-02 05:41:38 +00001495 case Instruction::Xor:
1496 // If the RHS of the xor is a signbit, then this is just an add.
1497 // Instcombine turns add of signbit into xor as a strength reduction step.
1498 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
1499 if (CI->getValue().isSignBit())
1500 return SCEVAddExpr::get(getSCEV(I->getOperand(0)),
1501 getSCEV(I->getOperand(1)));
1502 }
1503 break;
1504
Chris Lattner53e677a2004-04-02 20:23:17 +00001505 case Instruction::Shl:
1506 // Turn shift left of a constant amount into a multiply.
1507 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
Zhou Shengfdc1e162007-04-07 17:40:57 +00001508 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
1509 Constant *X = ConstantInt::get(
1510 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
Chris Lattner53e677a2004-04-02 20:23:17 +00001511 return SCEVMulExpr::get(getSCEV(I->getOperand(0)), getSCEV(X));
1512 }
1513 break;
1514
Reid Spencer3da59db2006-11-27 01:05:10 +00001515 case Instruction::Trunc:
Chris Lattnerb2f3e702007-01-15 01:58:56 +00001516 return SCEVTruncateExpr::get(getSCEV(I->getOperand(0)), I->getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00001517
1518 case Instruction::ZExt:
Chris Lattnerb2f3e702007-01-15 01:58:56 +00001519 return SCEVZeroExtendExpr::get(getSCEV(I->getOperand(0)), I->getType());
Reid Spencer3da59db2006-11-27 01:05:10 +00001520
Dan Gohmand19534a2007-06-15 14:38:12 +00001521 case Instruction::SExt:
1522 return SCEVSignExtendExpr::get(getSCEV(I->getOperand(0)), I->getType());
1523
Reid Spencer3da59db2006-11-27 01:05:10 +00001524 case Instruction::BitCast:
1525 // BitCasts are no-op casts so we just eliminate the cast.
Chris Lattner42a75512007-01-15 02:27:26 +00001526 if (I->getType()->isInteger() &&
1527 I->getOperand(0)->getType()->isInteger())
Chris Lattner82e8a8f2006-12-11 00:12:31 +00001528 return getSCEV(I->getOperand(0));
1529 break;
Chris Lattner53e677a2004-04-02 20:23:17 +00001530
1531 case Instruction::PHI:
1532 return createNodeForPHI(cast<PHINode>(I));
1533
1534 default: // We cannot analyze this expression.
1535 break;
1536 }
1537 }
1538
1539 return SCEVUnknown::get(V);
1540}
1541
1542
1543
1544//===----------------------------------------------------------------------===//
1545// Iteration Count Computation Code
1546//
1547
1548/// getIterationCount - If the specified loop has a predictable iteration
1549/// count, return it. Note that it is not valid to call this method on a
1550/// loop without a loop-invariant iteration count.
1551SCEVHandle ScalarEvolutionsImpl::getIterationCount(const Loop *L) {
1552 std::map<const Loop*, SCEVHandle>::iterator I = IterationCounts.find(L);
1553 if (I == IterationCounts.end()) {
1554 SCEVHandle ItCount = ComputeIterationCount(L);
1555 I = IterationCounts.insert(std::make_pair(L, ItCount)).first;
1556 if (ItCount != UnknownValue) {
1557 assert(ItCount->isLoopInvariant(L) &&
1558 "Computed trip count isn't loop invariant for loop!");
1559 ++NumTripCountsComputed;
1560 } else if (isa<PHINode>(L->getHeader()->begin())) {
1561 // Only count loops that have phi nodes as not being computable.
1562 ++NumTripCountsNotComputed;
1563 }
1564 }
1565 return I->second;
1566}
1567
1568/// ComputeIterationCount - Compute the number of times the specified loop
1569/// will iterate.
1570SCEVHandle ScalarEvolutionsImpl::ComputeIterationCount(const Loop *L) {
1571 // If the loop has a non-one exit block count, we can't analyze it.
Devang Patelb7211a22007-08-21 00:31:24 +00001572 SmallVector<BasicBlock*, 8> ExitBlocks;
Chris Lattnerf1ab4b42004-04-18 22:14:10 +00001573 L->getExitBlocks(ExitBlocks);
1574 if (ExitBlocks.size() != 1) return UnknownValue;
Chris Lattner53e677a2004-04-02 20:23:17 +00001575
1576 // Okay, there is one exit block. Try to find the condition that causes the
1577 // loop to be exited.
Chris Lattnerf1ab4b42004-04-18 22:14:10 +00001578 BasicBlock *ExitBlock = ExitBlocks[0];
Chris Lattner53e677a2004-04-02 20:23:17 +00001579
1580 BasicBlock *ExitingBlock = 0;
1581 for (pred_iterator PI = pred_begin(ExitBlock), E = pred_end(ExitBlock);
1582 PI != E; ++PI)
1583 if (L->contains(*PI)) {
1584 if (ExitingBlock == 0)
1585 ExitingBlock = *PI;
1586 else
1587 return UnknownValue; // More than one block exiting!
1588 }
1589 assert(ExitingBlock && "No exits from loop, something is broken!");
1590
1591 // Okay, we've computed the exiting block. See what condition causes us to
1592 // exit.
1593 //
1594 // FIXME: we should be able to handle switch instructions (with a single exit)
Chris Lattner53e677a2004-04-02 20:23:17 +00001595 BranchInst *ExitBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
1596 if (ExitBr == 0) return UnknownValue;
1597 assert(ExitBr->isConditional() && "If unconditional, it can't be in loop!");
Chris Lattner8b0e3602007-01-07 02:24:26 +00001598
1599 // At this point, we know we have a conditional branch that determines whether
1600 // the loop is exited. However, we don't know if the branch is executed each
1601 // time through the loop. If not, then the execution count of the branch will
1602 // not be equal to the trip count of the loop.
1603 //
1604 // Currently we check for this by checking to see if the Exit branch goes to
1605 // the loop header. If so, we know it will always execute the same number of
Chris Lattner192e4032007-01-14 01:24:47 +00001606 // times as the loop. We also handle the case where the exit block *is* the
1607 // loop header. This is common for un-rotated loops. More extensive analysis
1608 // could be done to handle more cases here.
Chris Lattner8b0e3602007-01-07 02:24:26 +00001609 if (ExitBr->getSuccessor(0) != L->getHeader() &&
Chris Lattner192e4032007-01-14 01:24:47 +00001610 ExitBr->getSuccessor(1) != L->getHeader() &&
1611 ExitBr->getParent() != L->getHeader())
Chris Lattner8b0e3602007-01-07 02:24:26 +00001612 return UnknownValue;
1613
Reid Spencere4d87aa2006-12-23 06:05:41 +00001614 ICmpInst *ExitCond = dyn_cast<ICmpInst>(ExitBr->getCondition());
1615
1616 // If its not an integer comparison then compute it the hard way.
1617 // Note that ICmpInst deals with pointer comparisons too so we must check
1618 // the type of the operand.
Chris Lattner8b0e3602007-01-07 02:24:26 +00001619 if (ExitCond == 0 || isa<PointerType>(ExitCond->getOperand(0)->getType()))
Chris Lattner7980fb92004-04-17 18:36:24 +00001620 return ComputeIterationCountExhaustively(L, ExitBr->getCondition(),
1621 ExitBr->getSuccessor(0) == ExitBlock);
Chris Lattner53e677a2004-04-02 20:23:17 +00001622
Reid Spencere4d87aa2006-12-23 06:05:41 +00001623 // If the condition was exit on true, convert the condition to exit on false
1624 ICmpInst::Predicate Cond;
Chris Lattner673e02b2004-10-12 01:49:27 +00001625 if (ExitBr->getSuccessor(1) == ExitBlock)
Reid Spencere4d87aa2006-12-23 06:05:41 +00001626 Cond = ExitCond->getPredicate();
Chris Lattner673e02b2004-10-12 01:49:27 +00001627 else
Reid Spencere4d87aa2006-12-23 06:05:41 +00001628 Cond = ExitCond->getInversePredicate();
Chris Lattner673e02b2004-10-12 01:49:27 +00001629
1630 // Handle common loops like: for (X = "string"; *X; ++X)
1631 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
1632 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
1633 SCEVHandle ItCnt =
1634 ComputeLoadConstantCompareIterationCount(LI, RHS, L, Cond);
1635 if (!isa<SCEVCouldNotCompute>(ItCnt)) return ItCnt;
1636 }
1637
Chris Lattner53e677a2004-04-02 20:23:17 +00001638 SCEVHandle LHS = getSCEV(ExitCond->getOperand(0));
1639 SCEVHandle RHS = getSCEV(ExitCond->getOperand(1));
1640
1641 // Try to evaluate any dependencies out of the loop.
1642 SCEVHandle Tmp = getSCEVAtScope(LHS, L);
1643 if (!isa<SCEVCouldNotCompute>(Tmp)) LHS = Tmp;
1644 Tmp = getSCEVAtScope(RHS, L);
1645 if (!isa<SCEVCouldNotCompute>(Tmp)) RHS = Tmp;
1646
Reid Spencere4d87aa2006-12-23 06:05:41 +00001647 // At this point, we would like to compute how many iterations of the
1648 // loop the predicate will return true for these inputs.
Chris Lattner53e677a2004-04-02 20:23:17 +00001649 if (isa<SCEVConstant>(LHS) && !isa<SCEVConstant>(RHS)) {
1650 // If there is a constant, force it into the RHS.
1651 std::swap(LHS, RHS);
Reid Spencere4d87aa2006-12-23 06:05:41 +00001652 Cond = ICmpInst::getSwappedPredicate(Cond);
Chris Lattner53e677a2004-04-02 20:23:17 +00001653 }
1654
1655 // FIXME: think about handling pointer comparisons! i.e.:
1656 // while (P != P+100) ++P;
1657
1658 // If we have a comparison of a chrec against a constant, try to use value
1659 // ranges to answer this query.
1660 if (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
1661 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
1662 if (AddRec->getLoop() == L) {
1663 // Form the comparison range using the constant of the correct type so
1664 // that the ConstantRange class knows to do a signed or unsigned
1665 // comparison.
1666 ConstantInt *CompVal = RHSC->getValue();
1667 const Type *RealTy = ExitCond->getOperand(0)->getType();
Reid Spencer4da49122006-12-12 05:05:00 +00001668 CompVal = dyn_cast<ConstantInt>(
Reid Spencerb6ba3e62006-12-12 09:17:50 +00001669 ConstantExpr::getBitCast(CompVal, RealTy));
Chris Lattner53e677a2004-04-02 20:23:17 +00001670 if (CompVal) {
1671 // Form the constant range.
Reid Spencerc6aedf72007-02-28 22:03:51 +00001672 ConstantRange CompRange(
1673 ICmpInst::makeConstantRange(Cond, CompVal->getValue()));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001674
Nick Lewyckyeefdebe2007-07-16 02:08:00 +00001675 SCEVHandle Ret = AddRec->getNumIterationsInRange(CompRange);
Chris Lattner53e677a2004-04-02 20:23:17 +00001676 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
1677 }
1678 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001679
Chris Lattner53e677a2004-04-02 20:23:17 +00001680 switch (Cond) {
Reid Spencere4d87aa2006-12-23 06:05:41 +00001681 case ICmpInst::ICMP_NE: { // while (X != Y)
Chris Lattner53e677a2004-04-02 20:23:17 +00001682 // Convert to: while (X-Y != 0)
Reid Spencere4d87aa2006-12-23 06:05:41 +00001683 SCEVHandle TC = HowFarToZero(SCEV::getMinusSCEV(LHS, RHS), L);
1684 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
Chris Lattner53e677a2004-04-02 20:23:17 +00001685 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00001686 }
1687 case ICmpInst::ICMP_EQ: {
Chris Lattner53e677a2004-04-02 20:23:17 +00001688 // Convert to: while (X-Y == 0) // while (X == Y)
Reid Spencere4d87aa2006-12-23 06:05:41 +00001689 SCEVHandle TC = HowFarToNonZero(SCEV::getMinusSCEV(LHS, RHS), L);
1690 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
Chris Lattner53e677a2004-04-02 20:23:17 +00001691 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00001692 }
1693 case ICmpInst::ICMP_SLT: {
Nick Lewyckyd6dac0e2007-08-06 19:21:00 +00001694 SCEVHandle TC = HowManyLessThans(LHS, RHS, L, true);
Reid Spencere4d87aa2006-12-23 06:05:41 +00001695 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
Chris Lattnerdb25de42005-08-15 23:33:51 +00001696 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00001697 }
1698 case ICmpInst::ICMP_SGT: {
Nick Lewyckyeefdebe2007-07-16 02:08:00 +00001699 SCEVHandle TC = HowManyLessThans(SCEV::getNegativeSCEV(LHS),
Nick Lewyckyd6dac0e2007-08-06 19:21:00 +00001700 SCEV::getNegativeSCEV(RHS), L, true);
1701 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
1702 break;
1703 }
1704 case ICmpInst::ICMP_ULT: {
1705 SCEVHandle TC = HowManyLessThans(LHS, RHS, L, false);
1706 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
1707 break;
1708 }
1709 case ICmpInst::ICMP_UGT: {
1710 SCEVHandle TC = HowManyLessThans(SCEV::getNegativeSCEV(LHS),
1711 SCEV::getNegativeSCEV(RHS), L, false);
Reid Spencere4d87aa2006-12-23 06:05:41 +00001712 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
Chris Lattnerdb25de42005-08-15 23:33:51 +00001713 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00001714 }
Chris Lattner53e677a2004-04-02 20:23:17 +00001715 default:
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00001716#if 0
Bill Wendlinge8156192006-12-07 01:30:32 +00001717 cerr << "ComputeIterationCount ";
Chris Lattner53e677a2004-04-02 20:23:17 +00001718 if (ExitCond->getOperand(0)->getType()->isUnsigned())
Bill Wendlinge8156192006-12-07 01:30:32 +00001719 cerr << "[unsigned] ";
1720 cerr << *LHS << " "
Reid Spencere4d87aa2006-12-23 06:05:41 +00001721 << Instruction::getOpcodeName(Instruction::ICmp)
1722 << " " << *RHS << "\n";
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00001723#endif
Chris Lattnere34c0b42004-04-03 00:43:03 +00001724 break;
Chris Lattner53e677a2004-04-02 20:23:17 +00001725 }
Chris Lattner7980fb92004-04-17 18:36:24 +00001726 return ComputeIterationCountExhaustively(L, ExitCond,
Reid Spencere4d87aa2006-12-23 06:05:41 +00001727 ExitBr->getSuccessor(0) == ExitBlock);
Chris Lattner7980fb92004-04-17 18:36:24 +00001728}
1729
Chris Lattner673e02b2004-10-12 01:49:27 +00001730static ConstantInt *
Dan Gohman9a6ae962007-07-09 15:25:17 +00001731EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C) {
1732 SCEVHandle InVal = SCEVConstant::get(C);
Chris Lattner673e02b2004-10-12 01:49:27 +00001733 SCEVHandle Val = AddRec->evaluateAtIteration(InVal);
1734 assert(isa<SCEVConstant>(Val) &&
1735 "Evaluation of SCEV at constant didn't fold correctly?");
1736 return cast<SCEVConstant>(Val)->getValue();
1737}
1738
1739/// GetAddressedElementFromGlobal - Given a global variable with an initializer
1740/// and a GEP expression (missing the pointer index) indexing into it, return
1741/// the addressed element of the initializer or null if the index expression is
1742/// invalid.
1743static Constant *
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001744GetAddressedElementFromGlobal(GlobalVariable *GV,
Chris Lattner673e02b2004-10-12 01:49:27 +00001745 const std::vector<ConstantInt*> &Indices) {
1746 Constant *Init = GV->getInitializer();
1747 for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
Reid Spencerb83eb642006-10-20 07:07:24 +00001748 uint64_t Idx = Indices[i]->getZExtValue();
Chris Lattner673e02b2004-10-12 01:49:27 +00001749 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
1750 assert(Idx < CS->getNumOperands() && "Bad struct index!");
1751 Init = cast<Constant>(CS->getOperand(Idx));
1752 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
1753 if (Idx >= CA->getNumOperands()) return 0; // Bogus program
1754 Init = cast<Constant>(CA->getOperand(Idx));
1755 } else if (isa<ConstantAggregateZero>(Init)) {
1756 if (const StructType *STy = dyn_cast<StructType>(Init->getType())) {
1757 assert(Idx < STy->getNumElements() && "Bad struct index!");
1758 Init = Constant::getNullValue(STy->getElementType(Idx));
1759 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Init->getType())) {
1760 if (Idx >= ATy->getNumElements()) return 0; // Bogus program
1761 Init = Constant::getNullValue(ATy->getElementType());
1762 } else {
1763 assert(0 && "Unknown constant aggregate type!");
1764 }
1765 return 0;
1766 } else {
1767 return 0; // Unknown initializer type
1768 }
1769 }
1770 return Init;
1771}
1772
1773/// ComputeLoadConstantCompareIterationCount - Given an exit condition of
1774/// 'setcc load X, cst', try to se if we can compute the trip count.
1775SCEVHandle ScalarEvolutionsImpl::
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001776ComputeLoadConstantCompareIterationCount(LoadInst *LI, Constant *RHS,
Reid Spencere4d87aa2006-12-23 06:05:41 +00001777 const Loop *L,
1778 ICmpInst::Predicate predicate) {
Chris Lattner673e02b2004-10-12 01:49:27 +00001779 if (LI->isVolatile()) return UnknownValue;
1780
1781 // Check to see if the loaded pointer is a getelementptr of a global.
1782 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
1783 if (!GEP) return UnknownValue;
1784
1785 // Make sure that it is really a constant global we are gepping, with an
1786 // initializer, and make sure the first IDX is really 0.
1787 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
1788 if (!GV || !GV->isConstant() || !GV->hasInitializer() ||
1789 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
1790 !cast<Constant>(GEP->getOperand(1))->isNullValue())
1791 return UnknownValue;
1792
1793 // Okay, we allow one non-constant index into the GEP instruction.
1794 Value *VarIdx = 0;
1795 std::vector<ConstantInt*> Indexes;
1796 unsigned VarIdxNum = 0;
1797 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
1798 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
1799 Indexes.push_back(CI);
1800 } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
1801 if (VarIdx) return UnknownValue; // Multiple non-constant idx's.
1802 VarIdx = GEP->getOperand(i);
1803 VarIdxNum = i-2;
1804 Indexes.push_back(0);
1805 }
1806
1807 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
1808 // Check to see if X is a loop variant variable value now.
1809 SCEVHandle Idx = getSCEV(VarIdx);
1810 SCEVHandle Tmp = getSCEVAtScope(Idx, L);
1811 if (!isa<SCEVCouldNotCompute>(Tmp)) Idx = Tmp;
1812
1813 // We can only recognize very limited forms of loop index expressions, in
1814 // particular, only affine AddRec's like {C1,+,C2}.
1815 SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
1816 if (!IdxExpr || !IdxExpr->isAffine() || IdxExpr->isLoopInvariant(L) ||
1817 !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
1818 !isa<SCEVConstant>(IdxExpr->getOperand(1)))
1819 return UnknownValue;
1820
1821 unsigned MaxSteps = MaxBruteForceIterations;
1822 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
Reid Spencerb83eb642006-10-20 07:07:24 +00001823 ConstantInt *ItCst =
Reid Spencerc5b206b2006-12-31 05:48:39 +00001824 ConstantInt::get(IdxExpr->getType(), IterationNum);
Chris Lattner673e02b2004-10-12 01:49:27 +00001825 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst);
1826
1827 // Form the GEP offset.
1828 Indexes[VarIdxNum] = Val;
1829
1830 Constant *Result = GetAddressedElementFromGlobal(GV, Indexes);
1831 if (Result == 0) break; // Cannot compute!
1832
1833 // Evaluate the condition for this iteration.
Reid Spencere4d87aa2006-12-23 06:05:41 +00001834 Result = ConstantExpr::getICmp(predicate, Result, RHS);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00001835 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure
Reid Spencere8019bb2007-03-01 07:25:48 +00001836 if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
Chris Lattner673e02b2004-10-12 01:49:27 +00001837#if 0
Bill Wendlinge8156192006-12-07 01:30:32 +00001838 cerr << "\n***\n*** Computed loop count " << *ItCst
1839 << "\n*** From global " << *GV << "*** BB: " << *L->getHeader()
1840 << "***\n";
Chris Lattner673e02b2004-10-12 01:49:27 +00001841#endif
1842 ++NumArrayLenItCounts;
1843 return SCEVConstant::get(ItCst); // Found terminating iteration!
1844 }
1845 }
1846 return UnknownValue;
1847}
1848
1849
Chris Lattner3221ad02004-04-17 22:58:41 +00001850/// CanConstantFold - Return true if we can constant fold an instruction of the
1851/// specified type, assuming that all operands were constants.
1852static bool CanConstantFold(const Instruction *I) {
Reid Spencer832254e2007-02-02 02:16:23 +00001853 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
Chris Lattner3221ad02004-04-17 22:58:41 +00001854 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I))
1855 return true;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001856
Chris Lattner3221ad02004-04-17 22:58:41 +00001857 if (const CallInst *CI = dyn_cast<CallInst>(I))
1858 if (const Function *F = CI->getCalledFunction())
1859 return canConstantFoldCallTo((Function*)F); // FIXME: elim cast
1860 return false;
Chris Lattner7980fb92004-04-17 18:36:24 +00001861}
1862
Chris Lattner3221ad02004-04-17 22:58:41 +00001863/// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
1864/// in the loop that V is derived from. We allow arbitrary operations along the
1865/// way, but the operands of an operation must either be constants or a value
1866/// derived from a constant PHI. If this expression does not fit with these
1867/// constraints, return null.
1868static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
1869 // If this is not an instruction, or if this is an instruction outside of the
1870 // loop, it can't be derived from a loop PHI.
1871 Instruction *I = dyn_cast<Instruction>(V);
1872 if (I == 0 || !L->contains(I->getParent())) return 0;
1873
1874 if (PHINode *PN = dyn_cast<PHINode>(I))
1875 if (L->getHeader() == I->getParent())
1876 return PN;
1877 else
1878 // We don't currently keep track of the control flow needed to evaluate
1879 // PHIs, so we cannot handle PHIs inside of loops.
1880 return 0;
1881
1882 // If we won't be able to constant fold this expression even if the operands
1883 // are constants, return early.
1884 if (!CanConstantFold(I)) return 0;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001885
Chris Lattner3221ad02004-04-17 22:58:41 +00001886 // Otherwise, we can evaluate this instruction if all of its operands are
1887 // constant or derived from a PHI node themselves.
1888 PHINode *PHI = 0;
1889 for (unsigned Op = 0, e = I->getNumOperands(); Op != e; ++Op)
1890 if (!(isa<Constant>(I->getOperand(Op)) ||
1891 isa<GlobalValue>(I->getOperand(Op)))) {
1892 PHINode *P = getConstantEvolvingPHI(I->getOperand(Op), L);
1893 if (P == 0) return 0; // Not evolving from PHI
1894 if (PHI == 0)
1895 PHI = P;
1896 else if (PHI != P)
1897 return 0; // Evolving from multiple different PHIs.
1898 }
1899
1900 // This is a expression evolving from a constant PHI!
1901 return PHI;
1902}
1903
1904/// EvaluateExpression - Given an expression that passes the
1905/// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
1906/// in the loop has the value PHIVal. If we can't fold this expression for some
1907/// reason, return null.
1908static Constant *EvaluateExpression(Value *V, Constant *PHIVal) {
1909 if (isa<PHINode>(V)) return PHIVal;
Chris Lattner3221ad02004-04-17 22:58:41 +00001910 if (GlobalValue *GV = dyn_cast<GlobalValue>(V))
Reid Spencere8404342004-07-18 00:18:30 +00001911 return GV;
1912 if (Constant *C = dyn_cast<Constant>(V)) return C;
Chris Lattner3221ad02004-04-17 22:58:41 +00001913 Instruction *I = cast<Instruction>(V);
1914
1915 std::vector<Constant*> Operands;
1916 Operands.resize(I->getNumOperands());
1917
1918 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
1919 Operands[i] = EvaluateExpression(I->getOperand(i), PHIVal);
1920 if (Operands[i] == 0) return 0;
1921 }
1922
Chris Lattner2e3a1d12007-01-30 23:52:44 +00001923 return ConstantFoldInstOperands(I, &Operands[0], Operands.size());
Chris Lattner3221ad02004-04-17 22:58:41 +00001924}
1925
1926/// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
1927/// in the header of its containing loop, we know the loop executes a
1928/// constant number of times, and the PHI node is just a recurrence
1929/// involving constants, fold it.
1930Constant *ScalarEvolutionsImpl::
Reid Spencere8019bb2007-03-01 07:25:48 +00001931getConstantEvolutionLoopExitValue(PHINode *PN, const APInt& Its, const Loop *L){
Chris Lattner3221ad02004-04-17 22:58:41 +00001932 std::map<PHINode*, Constant*>::iterator I =
1933 ConstantEvolutionLoopExitValue.find(PN);
1934 if (I != ConstantEvolutionLoopExitValue.end())
1935 return I->second;
1936
Reid Spencere8019bb2007-03-01 07:25:48 +00001937 if (Its.ugt(APInt(Its.getBitWidth(),MaxBruteForceIterations)))
Chris Lattner3221ad02004-04-17 22:58:41 +00001938 return ConstantEvolutionLoopExitValue[PN] = 0; // Not going to evaluate it.
1939
1940 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
1941
1942 // Since the loop is canonicalized, the PHI node must have two entries. One
1943 // entry must be a constant (coming in from outside of the loop), and the
1944 // second must be derived from the same PHI.
1945 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
1946 Constant *StartCST =
1947 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
1948 if (StartCST == 0)
1949 return RetVal = 0; // Must be a constant.
1950
1951 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
1952 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
1953 if (PN2 != PN)
1954 return RetVal = 0; // Not derived from same PHI.
1955
1956 // Execute the loop symbolically to determine the exit value.
Reid Spencere8019bb2007-03-01 07:25:48 +00001957 if (Its.getActiveBits() >= 32)
1958 return RetVal = 0; // More than 2^32-1 iterations?? Not doing it!
Chris Lattner3221ad02004-04-17 22:58:41 +00001959
Reid Spencere8019bb2007-03-01 07:25:48 +00001960 unsigned NumIterations = Its.getZExtValue(); // must be in range
1961 unsigned IterationNum = 0;
Chris Lattner3221ad02004-04-17 22:58:41 +00001962 for (Constant *PHIVal = StartCST; ; ++IterationNum) {
1963 if (IterationNum == NumIterations)
1964 return RetVal = PHIVal; // Got exit value!
1965
1966 // Compute the value of the PHI node for the next iteration.
1967 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
1968 if (NextPHI == PHIVal)
1969 return RetVal = NextPHI; // Stopped evolving!
1970 if (NextPHI == 0)
1971 return 0; // Couldn't evaluate!
1972 PHIVal = NextPHI;
1973 }
1974}
1975
Chris Lattner7980fb92004-04-17 18:36:24 +00001976/// ComputeIterationCountExhaustively - If the trip is known to execute a
1977/// constant number of times (the condition evolves only from constants),
1978/// try to evaluate a few iterations of the loop until we get the exit
1979/// condition gets a value of ExitWhen (true or false). If we cannot
1980/// evaluate the trip count of the loop, return UnknownValue.
1981SCEVHandle ScalarEvolutionsImpl::
1982ComputeIterationCountExhaustively(const Loop *L, Value *Cond, bool ExitWhen) {
1983 PHINode *PN = getConstantEvolvingPHI(Cond, L);
1984 if (PN == 0) return UnknownValue;
1985
1986 // Since the loop is canonicalized, the PHI node must have two entries. One
1987 // entry must be a constant (coming in from outside of the loop), and the
1988 // second must be derived from the same PHI.
1989 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
1990 Constant *StartCST =
1991 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
1992 if (StartCST == 0) return UnknownValue; // Must be a constant.
1993
1994 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
1995 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
1996 if (PN2 != PN) return UnknownValue; // Not derived from same PHI.
1997
1998 // Okay, we find a PHI node that defines the trip count of this loop. Execute
1999 // the loop symbolically to determine when the condition gets a value of
2000 // "ExitWhen".
2001 unsigned IterationNum = 0;
2002 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis.
2003 for (Constant *PHIVal = StartCST;
2004 IterationNum != MaxIterations; ++IterationNum) {
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002005 ConstantInt *CondVal =
2006 dyn_cast_or_null<ConstantInt>(EvaluateExpression(Cond, PHIVal));
Chris Lattner3221ad02004-04-17 22:58:41 +00002007
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002008 // Couldn't symbolically evaluate.
Chris Lattneref3baf02007-01-12 18:28:58 +00002009 if (!CondVal) return UnknownValue;
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002010
Reid Spencere8019bb2007-03-01 07:25:48 +00002011 if (CondVal->getValue() == uint64_t(ExitWhen)) {
Chris Lattner3221ad02004-04-17 22:58:41 +00002012 ConstantEvolutionLoopExitValue[PN] = PHIVal;
Chris Lattner7980fb92004-04-17 18:36:24 +00002013 ++NumBruteForceTripCountsComputed;
Reid Spencerc5b206b2006-12-31 05:48:39 +00002014 return SCEVConstant::get(ConstantInt::get(Type::Int32Ty, IterationNum));
Chris Lattner7980fb92004-04-17 18:36:24 +00002015 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002016
Chris Lattner3221ad02004-04-17 22:58:41 +00002017 // Compute the value of the PHI node for the next iteration.
2018 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
2019 if (NextPHI == 0 || NextPHI == PHIVal)
Chris Lattner7980fb92004-04-17 18:36:24 +00002020 return UnknownValue; // Couldn't evaluate or not making progress...
Chris Lattner3221ad02004-04-17 22:58:41 +00002021 PHIVal = NextPHI;
Chris Lattner7980fb92004-04-17 18:36:24 +00002022 }
2023
2024 // Too many iterations were needed to evaluate.
Chris Lattner53e677a2004-04-02 20:23:17 +00002025 return UnknownValue;
2026}
2027
2028/// getSCEVAtScope - Compute the value of the specified expression within the
2029/// indicated loop (which may be null to indicate in no loop). If the
2030/// expression cannot be evaluated, return UnknownValue.
2031SCEVHandle ScalarEvolutionsImpl::getSCEVAtScope(SCEV *V, const Loop *L) {
2032 // FIXME: this should be turned into a virtual method on SCEV!
2033
Chris Lattner3221ad02004-04-17 22:58:41 +00002034 if (isa<SCEVConstant>(V)) return V;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002035
Chris Lattner3221ad02004-04-17 22:58:41 +00002036 // If this instruction is evolves from a constant-evolving PHI, compute the
2037 // exit value from the loop without using SCEVs.
2038 if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
2039 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
2040 const Loop *LI = this->LI[I->getParent()];
2041 if (LI && LI->getParentLoop() == L) // Looking for loop exit value.
2042 if (PHINode *PN = dyn_cast<PHINode>(I))
2043 if (PN->getParent() == LI->getHeader()) {
2044 // Okay, there is no closed form solution for the PHI node. Check
2045 // to see if the loop that contains it has a known iteration count.
2046 // If so, we may be able to force computation of the exit value.
2047 SCEVHandle IterationCount = getIterationCount(LI);
2048 if (SCEVConstant *ICC = dyn_cast<SCEVConstant>(IterationCount)) {
2049 // Okay, we know how many times the containing loop executes. If
2050 // this is a constant evolving PHI node, get the final value at
2051 // the specified iteration number.
2052 Constant *RV = getConstantEvolutionLoopExitValue(PN,
Reid Spencere8019bb2007-03-01 07:25:48 +00002053 ICC->getValue()->getValue(),
Chris Lattner3221ad02004-04-17 22:58:41 +00002054 LI);
2055 if (RV) return SCEVUnknown::get(RV);
2056 }
2057 }
2058
Reid Spencer09906f32006-12-04 21:33:23 +00002059 // Okay, this is an expression that we cannot symbolically evaluate
Chris Lattner3221ad02004-04-17 22:58:41 +00002060 // into a SCEV. Check to see if it's possible to symbolically evaluate
Reid Spencer09906f32006-12-04 21:33:23 +00002061 // the arguments into constants, and if so, try to constant propagate the
Chris Lattner3221ad02004-04-17 22:58:41 +00002062 // result. This is particularly useful for computing loop exit values.
2063 if (CanConstantFold(I)) {
2064 std::vector<Constant*> Operands;
2065 Operands.reserve(I->getNumOperands());
2066 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
2067 Value *Op = I->getOperand(i);
2068 if (Constant *C = dyn_cast<Constant>(Op)) {
2069 Operands.push_back(C);
Chris Lattner3221ad02004-04-17 22:58:41 +00002070 } else {
2071 SCEVHandle OpV = getSCEVAtScope(getSCEV(Op), L);
2072 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(OpV))
Reid Spencerd977d862006-12-12 23:36:14 +00002073 Operands.push_back(ConstantExpr::getIntegerCast(SC->getValue(),
2074 Op->getType(),
2075 false));
Chris Lattner3221ad02004-04-17 22:58:41 +00002076 else if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(OpV)) {
2077 if (Constant *C = dyn_cast<Constant>(SU->getValue()))
Reid Spencerd977d862006-12-12 23:36:14 +00002078 Operands.push_back(ConstantExpr::getIntegerCast(C,
2079 Op->getType(),
2080 false));
Chris Lattner3221ad02004-04-17 22:58:41 +00002081 else
2082 return V;
2083 } else {
2084 return V;
2085 }
2086 }
2087 }
Chris Lattner2e3a1d12007-01-30 23:52:44 +00002088 Constant *C =ConstantFoldInstOperands(I, &Operands[0], Operands.size());
2089 return SCEVUnknown::get(C);
Chris Lattner3221ad02004-04-17 22:58:41 +00002090 }
2091 }
2092
2093 // This is some other type of SCEVUnknown, just return it.
2094 return V;
2095 }
2096
Chris Lattner53e677a2004-04-02 20:23:17 +00002097 if (SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
2098 // Avoid performing the look-up in the common case where the specified
2099 // expression has no loop-variant portions.
2100 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
2101 SCEVHandle OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
2102 if (OpAtScope != Comm->getOperand(i)) {
2103 if (OpAtScope == UnknownValue) return UnknownValue;
2104 // Okay, at least one of these operands is loop variant but might be
2105 // foldable. Build a new instance of the folded commutative expression.
Chris Lattner3221ad02004-04-17 22:58:41 +00002106 std::vector<SCEVHandle> NewOps(Comm->op_begin(), Comm->op_begin()+i);
Chris Lattner53e677a2004-04-02 20:23:17 +00002107 NewOps.push_back(OpAtScope);
2108
2109 for (++i; i != e; ++i) {
2110 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
2111 if (OpAtScope == UnknownValue) return UnknownValue;
2112 NewOps.push_back(OpAtScope);
2113 }
2114 if (isa<SCEVAddExpr>(Comm))
2115 return SCEVAddExpr::get(NewOps);
2116 assert(isa<SCEVMulExpr>(Comm) && "Only know about add and mul!");
2117 return SCEVMulExpr::get(NewOps);
2118 }
2119 }
2120 // If we got here, all operands are loop invariant.
2121 return Comm;
2122 }
2123
Chris Lattner60a05cc2006-04-01 04:48:52 +00002124 if (SCEVSDivExpr *Div = dyn_cast<SCEVSDivExpr>(V)) {
2125 SCEVHandle LHS = getSCEVAtScope(Div->getLHS(), L);
Chris Lattner53e677a2004-04-02 20:23:17 +00002126 if (LHS == UnknownValue) return LHS;
Chris Lattner60a05cc2006-04-01 04:48:52 +00002127 SCEVHandle RHS = getSCEVAtScope(Div->getRHS(), L);
Chris Lattner53e677a2004-04-02 20:23:17 +00002128 if (RHS == UnknownValue) return RHS;
Chris Lattner60a05cc2006-04-01 04:48:52 +00002129 if (LHS == Div->getLHS() && RHS == Div->getRHS())
2130 return Div; // must be loop invariant
2131 return SCEVSDivExpr::get(LHS, RHS);
Chris Lattner53e677a2004-04-02 20:23:17 +00002132 }
2133
2134 // If this is a loop recurrence for a loop that does not contain L, then we
2135 // are dealing with the final value computed by the loop.
2136 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
2137 if (!L || !AddRec->getLoop()->contains(L->getHeader())) {
2138 // To evaluate this recurrence, we need to know how many times the AddRec
2139 // loop iterates. Compute this now.
2140 SCEVHandle IterationCount = getIterationCount(AddRec->getLoop());
2141 if (IterationCount == UnknownValue) return UnknownValue;
2142 IterationCount = getTruncateOrZeroExtend(IterationCount,
2143 AddRec->getType());
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002144
Chris Lattner53e677a2004-04-02 20:23:17 +00002145 // If the value is affine, simplify the expression evaluation to just
2146 // Start + Step*IterationCount.
2147 if (AddRec->isAffine())
2148 return SCEVAddExpr::get(AddRec->getStart(),
2149 SCEVMulExpr::get(IterationCount,
2150 AddRec->getOperand(1)));
2151
2152 // Otherwise, evaluate it the hard way.
2153 return AddRec->evaluateAtIteration(IterationCount);
2154 }
2155 return UnknownValue;
2156 }
2157
2158 //assert(0 && "Unknown SCEV type!");
2159 return UnknownValue;
2160}
2161
2162
2163/// SolveQuadraticEquation - Find the roots of the quadratic equation for the
2164/// given quadratic chrec {L,+,M,+,N}. This returns either the two roots (which
2165/// might be the same) or two SCEVCouldNotCompute objects.
2166///
2167static std::pair<SCEVHandle,SCEVHandle>
2168SolveQuadraticEquation(const SCEVAddRecExpr *AddRec) {
2169 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
Reid Spencere8019bb2007-03-01 07:25:48 +00002170 SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
2171 SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
2172 SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002173
Chris Lattner53e677a2004-04-02 20:23:17 +00002174 // We currently can only solve this if the coefficients are constants.
Reid Spencere8019bb2007-03-01 07:25:48 +00002175 if (!LC || !MC || !NC) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002176 SCEV *CNC = new SCEVCouldNotCompute();
2177 return std::make_pair(CNC, CNC);
2178 }
2179
Reid Spencere8019bb2007-03-01 07:25:48 +00002180 uint32_t BitWidth = LC->getValue()->getValue().getBitWidth();
Chris Lattnerfe560b82007-04-15 19:52:49 +00002181 const APInt &L = LC->getValue()->getValue();
2182 const APInt &M = MC->getValue()->getValue();
2183 const APInt &N = NC->getValue()->getValue();
Reid Spencere8019bb2007-03-01 07:25:48 +00002184 APInt Two(BitWidth, 2);
2185 APInt Four(BitWidth, 4);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002186
Reid Spencere8019bb2007-03-01 07:25:48 +00002187 {
2188 using namespace APIntOps;
Zhou Sheng414de4d2007-04-07 17:48:27 +00002189 const APInt& C = L;
Reid Spencere8019bb2007-03-01 07:25:48 +00002190 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
2191 // The B coefficient is M-N/2
2192 APInt B(M);
2193 B -= sdiv(N,Two);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002194
Reid Spencere8019bb2007-03-01 07:25:48 +00002195 // The A coefficient is N/2
Zhou Sheng414de4d2007-04-07 17:48:27 +00002196 APInt A(N.sdiv(Two));
Chris Lattner53e677a2004-04-02 20:23:17 +00002197
Reid Spencere8019bb2007-03-01 07:25:48 +00002198 // Compute the B^2-4ac term.
2199 APInt SqrtTerm(B);
2200 SqrtTerm *= B;
2201 SqrtTerm -= Four * (A * C);
Chris Lattner53e677a2004-04-02 20:23:17 +00002202
Reid Spencere8019bb2007-03-01 07:25:48 +00002203 // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest
2204 // integer value or else APInt::sqrt() will assert.
2205 APInt SqrtVal(SqrtTerm.sqrt());
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002206
Reid Spencere8019bb2007-03-01 07:25:48 +00002207 // Compute the two solutions for the quadratic formula.
2208 // The divisions must be performed as signed divisions.
2209 APInt NegB(-B);
Reid Spencer3e35c8d2007-04-16 02:24:41 +00002210 APInt TwoA( A << 1 );
Reid Spencere8019bb2007-03-01 07:25:48 +00002211 ConstantInt *Solution1 = ConstantInt::get((NegB + SqrtVal).sdiv(TwoA));
2212 ConstantInt *Solution2 = ConstantInt::get((NegB - SqrtVal).sdiv(TwoA));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002213
Dan Gohman9a6ae962007-07-09 15:25:17 +00002214 return std::make_pair(SCEVConstant::get(Solution1),
2215 SCEVConstant::get(Solution2));
Reid Spencere8019bb2007-03-01 07:25:48 +00002216 } // end APIntOps namespace
Chris Lattner53e677a2004-04-02 20:23:17 +00002217}
2218
2219/// HowFarToZero - Return the number of times a backedge comparing the specified
2220/// value to zero will execute. If not computable, return UnknownValue
2221SCEVHandle ScalarEvolutionsImpl::HowFarToZero(SCEV *V, const Loop *L) {
2222 // If the value is a constant
2223 if (SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
2224 // If the value is already zero, the branch will execute zero times.
Reid Spencercae57542007-03-02 00:28:52 +00002225 if (C->getValue()->isZero()) return C;
Chris Lattner53e677a2004-04-02 20:23:17 +00002226 return UnknownValue; // Otherwise it will loop infinitely.
2227 }
2228
2229 SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
2230 if (!AddRec || AddRec->getLoop() != L)
2231 return UnknownValue;
2232
2233 if (AddRec->isAffine()) {
2234 // If this is an affine expression the execution count of this branch is
2235 // equal to:
2236 //
2237 // (0 - Start/Step) iff Start % Step == 0
2238 //
2239 // Get the initial value for the loop.
2240 SCEVHandle Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
Chris Lattner4a2b23e2004-10-11 04:07:27 +00002241 if (isa<SCEVCouldNotCompute>(Start)) return UnknownValue;
Chris Lattner53e677a2004-04-02 20:23:17 +00002242 SCEVHandle Step = AddRec->getOperand(1);
2243
2244 Step = getSCEVAtScope(Step, L->getParentLoop());
2245
2246 // Figure out if Start % Step == 0.
2247 // FIXME: We should add DivExpr and RemExpr operations to our AST.
2248 if (SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step)) {
2249 if (StepC->getValue()->equalsInt(1)) // N % 1 == 0
Chris Lattnerbac5b462005-03-09 05:34:41 +00002250 return SCEV::getNegativeSCEV(Start); // 0 - Start/1 == -Start
Chris Lattner53e677a2004-04-02 20:23:17 +00002251 if (StepC->getValue()->isAllOnesValue()) // N % -1 == 0
2252 return Start; // 0 - Start/-1 == Start
2253
2254 // Check to see if Start is divisible by SC with no remainder.
2255 if (SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start)) {
2256 ConstantInt *StartCC = StartC->getValue();
2257 Constant *StartNegC = ConstantExpr::getNeg(StartCC);
Reid Spencer0a783f72006-11-02 01:53:59 +00002258 Constant *Rem = ConstantExpr::getSRem(StartNegC, StepC->getValue());
Chris Lattner53e677a2004-04-02 20:23:17 +00002259 if (Rem->isNullValue()) {
Reid Spencer1628cec2006-10-26 06:15:43 +00002260 Constant *Result =ConstantExpr::getSDiv(StartNegC,StepC->getValue());
Chris Lattner53e677a2004-04-02 20:23:17 +00002261 return SCEVUnknown::get(Result);
2262 }
2263 }
2264 }
Chris Lattner42a75512007-01-15 02:27:26 +00002265 } else if (AddRec->isQuadratic() && AddRec->getType()->isInteger()) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002266 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
2267 // the quadratic equation to solve it.
2268 std::pair<SCEVHandle,SCEVHandle> Roots = SolveQuadraticEquation(AddRec);
2269 SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
2270 SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
2271 if (R1) {
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00002272#if 0
Bill Wendlinge8156192006-12-07 01:30:32 +00002273 cerr << "HFTZ: " << *V << " - sol#1: " << *R1
2274 << " sol#2: " << *R2 << "\n";
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00002275#endif
Chris Lattner53e677a2004-04-02 20:23:17 +00002276 // Pick the smallest positive root value.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002277 if (ConstantInt *CB =
2278 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
Reid Spencere4d87aa2006-12-23 06:05:41 +00002279 R1->getValue(), R2->getValue()))) {
Reid Spencer579dca12007-01-12 04:24:46 +00002280 if (CB->getZExtValue() == false)
Chris Lattner53e677a2004-04-02 20:23:17 +00002281 std::swap(R1, R2); // R1 is the minimum root now.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002282
Chris Lattner53e677a2004-04-02 20:23:17 +00002283 // We can only use this value if the chrec ends up with an exact zero
2284 // value at this index. When solving for "X*X != 5", for example, we
2285 // should not accept a root of 2.
2286 SCEVHandle Val = AddRec->evaluateAtIteration(R1);
2287 if (SCEVConstant *EvalVal = dyn_cast<SCEVConstant>(Val))
Reid Spencercae57542007-03-02 00:28:52 +00002288 if (EvalVal->getValue()->isZero())
Chris Lattner53e677a2004-04-02 20:23:17 +00002289 return R1; // We found a quadratic root!
2290 }
2291 }
2292 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002293
Chris Lattner53e677a2004-04-02 20:23:17 +00002294 return UnknownValue;
2295}
2296
2297/// HowFarToNonZero - Return the number of times a backedge checking the
2298/// specified value for nonzero will execute. If not computable, return
2299/// UnknownValue
2300SCEVHandle ScalarEvolutionsImpl::HowFarToNonZero(SCEV *V, const Loop *L) {
2301 // Loops that look like: while (X == 0) are very strange indeed. We don't
2302 // handle them yet except for the trivial case. This could be expanded in the
2303 // future as needed.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002304
Chris Lattner53e677a2004-04-02 20:23:17 +00002305 // If the value is a constant, check to see if it is known to be non-zero
2306 // already. If so, the backedge will execute zero times.
2307 if (SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
2308 Constant *Zero = Constant::getNullValue(C->getValue()->getType());
Reid Spencere4d87aa2006-12-23 06:05:41 +00002309 Constant *NonZero =
2310 ConstantExpr::getICmp(ICmpInst::ICMP_NE, C->getValue(), Zero);
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002311 if (NonZero == ConstantInt::getTrue())
Chris Lattner53e677a2004-04-02 20:23:17 +00002312 return getSCEV(Zero);
2313 return UnknownValue; // Otherwise it will loop infinitely.
2314 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002315
Chris Lattner53e677a2004-04-02 20:23:17 +00002316 // We could implement others, but I really doubt anyone writes loops like
2317 // this, and if they did, they would already be constant folded.
2318 return UnknownValue;
2319}
2320
Chris Lattnerdb25de42005-08-15 23:33:51 +00002321/// HowManyLessThans - Return the number of times a backedge containing the
2322/// specified less-than comparison will execute. If not computable, return
2323/// UnknownValue.
2324SCEVHandle ScalarEvolutionsImpl::
Nick Lewyckyd6dac0e2007-08-06 19:21:00 +00002325HowManyLessThans(SCEV *LHS, SCEV *RHS, const Loop *L, bool isSigned) {
Chris Lattnerdb25de42005-08-15 23:33:51 +00002326 // Only handle: "ADDREC < LoopInvariant".
2327 if (!RHS->isLoopInvariant(L)) return UnknownValue;
2328
2329 SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS);
2330 if (!AddRec || AddRec->getLoop() != L)
2331 return UnknownValue;
2332
2333 if (AddRec->isAffine()) {
2334 // FORNOW: We only support unit strides.
2335 SCEVHandle One = SCEVUnknown::getIntegerSCEV(1, RHS->getType());
2336 if (AddRec->getOperand(1) != One)
2337 return UnknownValue;
2338
2339 // The number of iterations for "[n,+,1] < m", is m-n. However, we don't
2340 // know that m is >= n on input to the loop. If it is, the condition return
2341 // true zero times. What we really should return, for full generality, is
2342 // SMAX(0, m-n). Since we cannot check this, we will instead check for a
2343 // canonical loop form: most do-loops will have a check that dominates the
2344 // loop, that only enters the loop if [n-1]<m. If we can find this check,
2345 // we know that the SMAX will evaluate to m-n, because we know that m >= n.
2346
2347 // Search for the check.
2348 BasicBlock *Preheader = L->getLoopPreheader();
2349 BasicBlock *PreheaderDest = L->getHeader();
2350 if (Preheader == 0) return UnknownValue;
2351
2352 BranchInst *LoopEntryPredicate =
2353 dyn_cast<BranchInst>(Preheader->getTerminator());
2354 if (!LoopEntryPredicate) return UnknownValue;
2355
2356 // This might be a critical edge broken out. If the loop preheader ends in
2357 // an unconditional branch to the loop, check to see if the preheader has a
2358 // single predecessor, and if so, look for its terminator.
2359 while (LoopEntryPredicate->isUnconditional()) {
2360 PreheaderDest = Preheader;
2361 Preheader = Preheader->getSinglePredecessor();
2362 if (!Preheader) return UnknownValue; // Multiple preds.
2363
2364 LoopEntryPredicate =
2365 dyn_cast<BranchInst>(Preheader->getTerminator());
2366 if (!LoopEntryPredicate) return UnknownValue;
2367 }
2368
2369 // Now that we found a conditional branch that dominates the loop, check to
2370 // see if it is the comparison we are looking for.
Reid Spencere4d87aa2006-12-23 06:05:41 +00002371 if (ICmpInst *ICI = dyn_cast<ICmpInst>(LoopEntryPredicate->getCondition())){
2372 Value *PreCondLHS = ICI->getOperand(0);
2373 Value *PreCondRHS = ICI->getOperand(1);
2374 ICmpInst::Predicate Cond;
2375 if (LoopEntryPredicate->getSuccessor(0) == PreheaderDest)
2376 Cond = ICI->getPredicate();
2377 else
2378 Cond = ICI->getInversePredicate();
Chris Lattnerdb25de42005-08-15 23:33:51 +00002379
Reid Spencere4d87aa2006-12-23 06:05:41 +00002380 switch (Cond) {
2381 case ICmpInst::ICMP_UGT:
Nick Lewyckyd6dac0e2007-08-06 19:21:00 +00002382 if (isSigned) return UnknownValue;
Reid Spencere4d87aa2006-12-23 06:05:41 +00002383 std::swap(PreCondLHS, PreCondRHS);
2384 Cond = ICmpInst::ICMP_ULT;
Chris Lattnerdb25de42005-08-15 23:33:51 +00002385 break;
Reid Spencere4d87aa2006-12-23 06:05:41 +00002386 case ICmpInst::ICMP_SGT:
Nick Lewyckyd6dac0e2007-08-06 19:21:00 +00002387 if (!isSigned) return UnknownValue;
Reid Spencere4d87aa2006-12-23 06:05:41 +00002388 std::swap(PreCondLHS, PreCondRHS);
2389 Cond = ICmpInst::ICMP_SLT;
2390 break;
Nick Lewyckyd6dac0e2007-08-06 19:21:00 +00002391 case ICmpInst::ICMP_ULT:
2392 if (isSigned) return UnknownValue;
2393 break;
2394 case ICmpInst::ICMP_SLT:
2395 if (!isSigned) return UnknownValue;
2396 break;
2397 default:
2398 return UnknownValue;
Chris Lattnerdb25de42005-08-15 23:33:51 +00002399 }
Chris Lattnerdb25de42005-08-15 23:33:51 +00002400
Nick Lewyckyd6dac0e2007-08-06 19:21:00 +00002401 if (PreCondLHS->getType()->isInteger()) {
2402 if (RHS != getSCEV(PreCondRHS))
2403 return UnknownValue; // Not a comparison against 'm'.
Reid Spencere4d87aa2006-12-23 06:05:41 +00002404
Nick Lewyckyd6dac0e2007-08-06 19:21:00 +00002405 if (SCEV::getMinusSCEV(AddRec->getOperand(0), One)
2406 != getSCEV(PreCondLHS))
2407 return UnknownValue; // Not a comparison against 'n-1'.
2408 }
2409 else return UnknownValue;
Reid Spencere4d87aa2006-12-23 06:05:41 +00002410
2411 // cerr << "Computed Loop Trip Count as: "
2412 // << // *SCEV::getMinusSCEV(RHS, AddRec->getOperand(0)) << "\n";
2413 return SCEV::getMinusSCEV(RHS, AddRec->getOperand(0));
2414 }
2415 else
2416 return UnknownValue;
Chris Lattnerdb25de42005-08-15 23:33:51 +00002417 }
2418
2419 return UnknownValue;
2420}
2421
Chris Lattner53e677a2004-04-02 20:23:17 +00002422/// getNumIterationsInRange - Return the number of iterations of this loop that
2423/// produce values in the specified constant range. Another way of looking at
2424/// this is that it returns the first iteration number where the value is not in
2425/// the condition, thus computing the exit count. If the iteration count can't
2426/// be computed, an instance of SCEVCouldNotCompute is returned.
Nick Lewyckyeefdebe2007-07-16 02:08:00 +00002427SCEVHandle SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range) const {
Chris Lattner53e677a2004-04-02 20:23:17 +00002428 if (Range.isFullSet()) // Infinite loop.
2429 return new SCEVCouldNotCompute();
2430
2431 // If the start is a non-zero constant, shift the range to simplify things.
2432 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
Reid Spencercae57542007-03-02 00:28:52 +00002433 if (!SC->getValue()->isZero()) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002434 std::vector<SCEVHandle> Operands(op_begin(), op_end());
Chris Lattnerb06432c2004-04-23 21:29:03 +00002435 Operands[0] = SCEVUnknown::getIntegerSCEV(0, SC->getType());
Chris Lattner53e677a2004-04-02 20:23:17 +00002436 SCEVHandle Shifted = SCEVAddRecExpr::get(Operands, getLoop());
2437 if (SCEVAddRecExpr *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted))
2438 return ShiftedAddRec->getNumIterationsInRange(
Nick Lewyckyeefdebe2007-07-16 02:08:00 +00002439 Range.subtract(SC->getValue()->getValue()));
Chris Lattner53e677a2004-04-02 20:23:17 +00002440 // This is strange and shouldn't happen.
2441 return new SCEVCouldNotCompute();
2442 }
2443
2444 // The only time we can solve this is when we have all constant indices.
2445 // Otherwise, we cannot determine the overflow conditions.
2446 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
2447 if (!isa<SCEVConstant>(getOperand(i)))
2448 return new SCEVCouldNotCompute();
2449
2450
2451 // Okay at this point we know that all elements of the chrec are constants and
2452 // that the start element is zero.
2453
2454 // First check to see if the range contains zero. If not, the first
2455 // iteration exits.
Reid Spencera6e8a952007-03-01 07:54:15 +00002456 if (!Range.contains(APInt(getBitWidth(),0)))
Reid Spencer581b0d42007-02-28 19:57:34 +00002457 return SCEVConstant::get(ConstantInt::get(getType(),0));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002458
Chris Lattner53e677a2004-04-02 20:23:17 +00002459 if (isAffine()) {
2460 // If this is an affine expression then we have this situation:
2461 // Solve {0,+,A} in Range === Ax in Range
2462
Nick Lewyckyeefdebe2007-07-16 02:08:00 +00002463 // We know that zero is in the range. If A is positive then we know that
2464 // the upper value of the range must be the first possible exit value.
2465 // If A is negative then the lower of the range is the last possible loop
2466 // value. Also note that we already checked for a full range.
Reid Spencer581b0d42007-02-28 19:57:34 +00002467 APInt One(getBitWidth(),1);
Nick Lewyckyeefdebe2007-07-16 02:08:00 +00002468 APInt A = cast<SCEVConstant>(getOperand(1))->getValue()->getValue();
2469 APInt End = A.sge(One) ? (Range.getUpper() - One) : Range.getLower();
Chris Lattner53e677a2004-04-02 20:23:17 +00002470
Nick Lewyckyeefdebe2007-07-16 02:08:00 +00002471 // The exit value should be (End+A)/A.
2472 APInt ExitVal = (End + A).sdiv(A);
Reid Spencerc7cd7a02007-03-01 19:32:33 +00002473 ConstantInt *ExitValue = ConstantInt::get(ExitVal);
Chris Lattner53e677a2004-04-02 20:23:17 +00002474
2475 // Evaluate at the exit value. If we really did fall out of the valid
2476 // range, then we computed our trip count, otherwise wrap around or other
2477 // things must have happened.
2478 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue);
Reid Spencera6e8a952007-03-01 07:54:15 +00002479 if (Range.contains(Val->getValue()))
Chris Lattner53e677a2004-04-02 20:23:17 +00002480 return new SCEVCouldNotCompute(); // Something strange happened
2481
2482 // Ensure that the previous value is in the range. This is a sanity check.
Reid Spencer581b0d42007-02-28 19:57:34 +00002483 assert(Range.contains(
2484 EvaluateConstantChrecAtConstant(this,
Reid Spencerc7cd7a02007-03-01 19:32:33 +00002485 ConstantInt::get(ExitVal - One))->getValue()) &&
Chris Lattner53e677a2004-04-02 20:23:17 +00002486 "Linear scev computation is off in a bad way!");
Dan Gohman9a6ae962007-07-09 15:25:17 +00002487 return SCEVConstant::get(ExitValue);
Chris Lattner53e677a2004-04-02 20:23:17 +00002488 } else if (isQuadratic()) {
2489 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
2490 // quadratic equation to solve it. To do this, we must frame our problem in
2491 // terms of figuring out when zero is crossed, instead of when
2492 // Range.getUpper() is crossed.
2493 std::vector<SCEVHandle> NewOps(op_begin(), op_end());
Dan Gohman9a6ae962007-07-09 15:25:17 +00002494 NewOps[0] = SCEV::getNegativeSCEV(SCEVConstant::get(Range.getUpper()));
Chris Lattner53e677a2004-04-02 20:23:17 +00002495 SCEVHandle NewAddRec = SCEVAddRecExpr::get(NewOps, getLoop());
2496
2497 // Next, solve the constructed addrec
2498 std::pair<SCEVHandle,SCEVHandle> Roots =
2499 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec));
2500 SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
2501 SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
2502 if (R1) {
2503 // Pick the smallest positive root value.
Zhou Sheng6b6b6ef2007-01-11 12:24:14 +00002504 if (ConstantInt *CB =
2505 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
Reid Spencere4d87aa2006-12-23 06:05:41 +00002506 R1->getValue(), R2->getValue()))) {
Reid Spencer579dca12007-01-12 04:24:46 +00002507 if (CB->getZExtValue() == false)
Chris Lattner53e677a2004-04-02 20:23:17 +00002508 std::swap(R1, R2); // R1 is the minimum root now.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002509
Chris Lattner53e677a2004-04-02 20:23:17 +00002510 // Make sure the root is not off by one. The returned iteration should
2511 // not be in the range, but the previous one should be. When solving
2512 // for "X*X < 5", for example, we should not return a root of 2.
2513 ConstantInt *R1Val = EvaluateConstantChrecAtConstant(this,
2514 R1->getValue());
Reid Spencera6e8a952007-03-01 07:54:15 +00002515 if (Range.contains(R1Val->getValue())) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002516 // The next iteration must be out of the range...
Dan Gohman9a6ae962007-07-09 15:25:17 +00002517 ConstantInt *NextVal = ConstantInt::get(R1->getValue()->getValue()+1);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002518
Chris Lattner53e677a2004-04-02 20:23:17 +00002519 R1Val = EvaluateConstantChrecAtConstant(this, NextVal);
Reid Spencera6e8a952007-03-01 07:54:15 +00002520 if (!Range.contains(R1Val->getValue()))
Dan Gohman9a6ae962007-07-09 15:25:17 +00002521 return SCEVConstant::get(NextVal);
Chris Lattner53e677a2004-04-02 20:23:17 +00002522 return new SCEVCouldNotCompute(); // Something strange happened
2523 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002524
Chris Lattner53e677a2004-04-02 20:23:17 +00002525 // If R1 was not in the range, then it is a good return value. Make
2526 // sure that R1-1 WAS in the range though, just in case.
Dan Gohman9a6ae962007-07-09 15:25:17 +00002527 ConstantInt *NextVal = ConstantInt::get(R1->getValue()->getValue()-1);
Chris Lattner53e677a2004-04-02 20:23:17 +00002528 R1Val = EvaluateConstantChrecAtConstant(this, NextVal);
Reid Spencera6e8a952007-03-01 07:54:15 +00002529 if (Range.contains(R1Val->getValue()))
Chris Lattner53e677a2004-04-02 20:23:17 +00002530 return R1;
2531 return new SCEVCouldNotCompute(); // Something strange happened
2532 }
2533 }
2534 }
2535
2536 // Fallback, if this is a general polynomial, figure out the progression
2537 // through brute force: evaluate until we find an iteration that fails the
2538 // test. This is likely to be slow, but getting an accurate trip count is
2539 // incredibly important, we will be able to simplify the exit test a lot, and
2540 // we are almost guaranteed to get a trip count in this case.
2541 ConstantInt *TestVal = ConstantInt::get(getType(), 0);
Chris Lattner53e677a2004-04-02 20:23:17 +00002542 ConstantInt *EndVal = TestVal; // Stop when we wrap around.
2543 do {
2544 ++NumBruteForceEvaluations;
2545 SCEVHandle Val = evaluateAtIteration(SCEVConstant::get(TestVal));
2546 if (!isa<SCEVConstant>(Val)) // This shouldn't happen.
2547 return new SCEVCouldNotCompute();
2548
2549 // Check to see if we found the value!
Reid Spencera6e8a952007-03-01 07:54:15 +00002550 if (!Range.contains(cast<SCEVConstant>(Val)->getValue()->getValue()))
Chris Lattner53e677a2004-04-02 20:23:17 +00002551 return SCEVConstant::get(TestVal);
2552
2553 // Increment to test the next index.
Zhou Shengfdc1e162007-04-07 17:40:57 +00002554 TestVal = ConstantInt::get(TestVal->getValue()+1);
Chris Lattner53e677a2004-04-02 20:23:17 +00002555 } while (TestVal != EndVal);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002556
Chris Lattner53e677a2004-04-02 20:23:17 +00002557 return new SCEVCouldNotCompute();
2558}
2559
2560
2561
2562//===----------------------------------------------------------------------===//
2563// ScalarEvolution Class Implementation
2564//===----------------------------------------------------------------------===//
2565
2566bool ScalarEvolution::runOnFunction(Function &F) {
2567 Impl = new ScalarEvolutionsImpl(F, getAnalysis<LoopInfo>());
2568 return false;
2569}
2570
2571void ScalarEvolution::releaseMemory() {
2572 delete (ScalarEvolutionsImpl*)Impl;
2573 Impl = 0;
2574}
2575
2576void ScalarEvolution::getAnalysisUsage(AnalysisUsage &AU) const {
2577 AU.setPreservesAll();
Chris Lattner53e677a2004-04-02 20:23:17 +00002578 AU.addRequiredTransitive<LoopInfo>();
2579}
2580
2581SCEVHandle ScalarEvolution::getSCEV(Value *V) const {
2582 return ((ScalarEvolutionsImpl*)Impl)->getSCEV(V);
2583}
2584
Chris Lattnera0740fb2005-08-09 23:36:33 +00002585/// hasSCEV - Return true if the SCEV for this value has already been
2586/// computed.
2587bool ScalarEvolution::hasSCEV(Value *V) const {
Chris Lattner05bd3742005-08-10 00:59:40 +00002588 return ((ScalarEvolutionsImpl*)Impl)->hasSCEV(V);
Chris Lattnera0740fb2005-08-09 23:36:33 +00002589}
2590
2591
2592/// setSCEV - Insert the specified SCEV into the map of current SCEVs for
2593/// the specified value.
2594void ScalarEvolution::setSCEV(Value *V, const SCEVHandle &H) {
2595 ((ScalarEvolutionsImpl*)Impl)->setSCEV(V, H);
2596}
2597
2598
Chris Lattner53e677a2004-04-02 20:23:17 +00002599SCEVHandle ScalarEvolution::getIterationCount(const Loop *L) const {
2600 return ((ScalarEvolutionsImpl*)Impl)->getIterationCount(L);
2601}
2602
2603bool ScalarEvolution::hasLoopInvariantIterationCount(const Loop *L) const {
2604 return !isa<SCEVCouldNotCompute>(getIterationCount(L));
2605}
2606
2607SCEVHandle ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) const {
2608 return ((ScalarEvolutionsImpl*)Impl)->getSCEVAtScope(getSCEV(V), L);
2609}
2610
Dan Gohman5cec4db2007-06-19 14:28:31 +00002611void ScalarEvolution::deleteValueFromRecords(Value *V) const {
2612 return ((ScalarEvolutionsImpl*)Impl)->deleteValueFromRecords(V);
Chris Lattner53e677a2004-04-02 20:23:17 +00002613}
2614
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002615static void PrintLoopInfo(std::ostream &OS, const ScalarEvolution *SE,
Chris Lattner53e677a2004-04-02 20:23:17 +00002616 const Loop *L) {
2617 // Print all inner loops first
2618 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
2619 PrintLoopInfo(OS, SE, *I);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002620
Bill Wendlinge8156192006-12-07 01:30:32 +00002621 cerr << "Loop " << L->getHeader()->getName() << ": ";
Chris Lattnerf1ab4b42004-04-18 22:14:10 +00002622
Devang Patelb7211a22007-08-21 00:31:24 +00002623 SmallVector<BasicBlock*, 8> ExitBlocks;
Chris Lattnerf1ab4b42004-04-18 22:14:10 +00002624 L->getExitBlocks(ExitBlocks);
2625 if (ExitBlocks.size() != 1)
Bill Wendlinge8156192006-12-07 01:30:32 +00002626 cerr << "<multiple exits> ";
Chris Lattner53e677a2004-04-02 20:23:17 +00002627
2628 if (SE->hasLoopInvariantIterationCount(L)) {
Bill Wendlinge8156192006-12-07 01:30:32 +00002629 cerr << *SE->getIterationCount(L) << " iterations! ";
Chris Lattner53e677a2004-04-02 20:23:17 +00002630 } else {
Bill Wendlinge8156192006-12-07 01:30:32 +00002631 cerr << "Unpredictable iteration count. ";
Chris Lattner53e677a2004-04-02 20:23:17 +00002632 }
2633
Bill Wendlinge8156192006-12-07 01:30:32 +00002634 cerr << "\n";
Chris Lattner53e677a2004-04-02 20:23:17 +00002635}
2636
Reid Spencerce9653c2004-12-07 04:03:45 +00002637void ScalarEvolution::print(std::ostream &OS, const Module* ) const {
Chris Lattner53e677a2004-04-02 20:23:17 +00002638 Function &F = ((ScalarEvolutionsImpl*)Impl)->F;
2639 LoopInfo &LI = ((ScalarEvolutionsImpl*)Impl)->LI;
2640
2641 OS << "Classifying expressions for: " << F.getName() << "\n";
2642 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
Chris Lattner42a75512007-01-15 02:27:26 +00002643 if (I->getType()->isInteger()) {
Chris Lattner6ffe5512004-04-27 15:13:33 +00002644 OS << *I;
Chris Lattner53e677a2004-04-02 20:23:17 +00002645 OS << " --> ";
Chris Lattner6ffe5512004-04-27 15:13:33 +00002646 SCEVHandle SV = getSCEV(&*I);
Chris Lattner53e677a2004-04-02 20:23:17 +00002647 SV->print(OS);
2648 OS << "\t\t";
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002649
Chris Lattner42a75512007-01-15 02:27:26 +00002650 if ((*I).getType()->isInteger()) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002651 ConstantRange Bounds = SV->getValueRange();
2652 if (!Bounds.isFullSet())
2653 OS << "Bounds: " << Bounds << " ";
2654 }
2655
Chris Lattner6ffe5512004-04-27 15:13:33 +00002656 if (const Loop *L = LI.getLoopFor((*I).getParent())) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002657 OS << "Exits: ";
Chris Lattner6ffe5512004-04-27 15:13:33 +00002658 SCEVHandle ExitValue = getSCEVAtScope(&*I, L->getParentLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00002659 if (isa<SCEVCouldNotCompute>(ExitValue)) {
2660 OS << "<<Unknown>>";
2661 } else {
2662 OS << *ExitValue;
2663 }
2664 }
2665
2666
2667 OS << "\n";
2668 }
2669
2670 OS << "Determining loop execution counts for: " << F.getName() << "\n";
2671 for (LoopInfo::iterator I = LI.begin(), E = LI.end(); I != E; ++I)
2672 PrintLoopInfo(OS, this, *I);
2673}
2674