blob: 8c809f8c5ac7b3e28fb4989588a1466faa615691 [file] [log] [blame]
Chris Lattner53e677a2004-04-02 20:23:17 +00001//===- ScalarEvolution.cpp - Scalar Evolution Analysis ----------*- C++ -*-===//
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002//
Chris Lattner53e677a2004-04-02 20:23:17 +00003// The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00007//
Chris Lattner53e677a2004-04-02 20:23:17 +00008//===----------------------------------------------------------------------===//
9//
10// This file contains the implementation of the scalar evolution analysis
11// engine, which is used primarily to analyze expressions involving induction
12// variables in loops.
13//
14// There are several aspects to this library. First is the representation of
15// scalar expressions, which are represented as subclasses of the SCEV class.
16// These classes are used to represent certain types of subexpressions that we
17// can handle. These classes are reference counted, managed by the SCEVHandle
18// class. We only create one SCEV of a particular shape, so pointer-comparisons
19// for equality are legal.
20//
21// One important aspect of the SCEV objects is that they are never cyclic, even
22// if there is a cycle in the dataflow for an expression (ie, a PHI node). If
23// the PHI node is one of the idioms that we can represent (e.g., a polynomial
24// recurrence) then we represent it directly as a recurrence node, otherwise we
25// represent it as a SCEVUnknown node.
26//
27// In addition to being able to represent expressions of various types, we also
28// have folders that are used to build the *canonical* representation for a
29// particular expression. These folders are capable of using a variety of
30// rewrite rules to simplify the expressions.
Misha Brukman2b37d7c2005-04-21 21:13:18 +000031//
Chris Lattner53e677a2004-04-02 20:23:17 +000032// Once the folders are defined, we can implement the more interesting
33// higher-level code, such as the code that recognizes PHI nodes of various
34// types, computes the execution count of a loop, etc.
35//
Chris Lattner53e677a2004-04-02 20:23:17 +000036// TODO: We should use these routines and value representations to implement
37// dependence analysis!
38//
39//===----------------------------------------------------------------------===//
40//
41// There are several good references for the techniques used in this analysis.
42//
43// Chains of recurrences -- a method to expedite the evaluation
44// of closed-form functions
45// Olaf Bachmann, Paul S. Wang, Eugene V. Zima
46//
47// On computational properties of chains of recurrences
48// Eugene V. Zima
49//
50// Symbolic Evaluation of Chains of Recurrences for Loop Optimization
51// Robert A. van Engelen
52//
53// Efficient Symbolic Analysis for Optimizing Compilers
54// Robert A. van Engelen
55//
56// Using the chains of recurrences algebra for data dependence testing and
57// induction variable substitution
58// MS Thesis, Johnie Birch
59//
60//===----------------------------------------------------------------------===//
61
Chris Lattner0a7f98c2004-04-15 15:07:24 +000062#include "llvm/Analysis/ScalarEvolutionExpressions.h"
Chris Lattner53e677a2004-04-02 20:23:17 +000063#include "llvm/Constants.h"
64#include "llvm/DerivedTypes.h"
Chris Lattner673e02b2004-10-12 01:49:27 +000065#include "llvm/GlobalVariable.h"
Chris Lattner53e677a2004-04-02 20:23:17 +000066#include "llvm/Instructions.h"
John Criswella1156432005-10-27 15:54:34 +000067#include "llvm/Analysis/ConstantFolding.h"
Chris Lattner53e677a2004-04-02 20:23:17 +000068#include "llvm/Analysis/LoopInfo.h"
69#include "llvm/Assembly/Writer.h"
70#include "llvm/Transforms/Scalar.h"
71#include "llvm/Support/CFG.h"
Chris Lattner95255282006-06-28 23:17:24 +000072#include "llvm/Support/CommandLine.h"
Chris Lattnerb3364092006-10-04 21:49:37 +000073#include "llvm/Support/Compiler.h"
Chris Lattner53e677a2004-04-02 20:23:17 +000074#include "llvm/Support/ConstantRange.h"
75#include "llvm/Support/InstIterator.h"
Chris Lattnerb3364092006-10-04 21:49:37 +000076#include "llvm/Support/ManagedStatic.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000077#include "llvm/ADT/Statistic.h"
Chris Lattner72382102006-01-22 23:19:18 +000078#include <iostream>
Alkis Evlogimenos20aa4742004-09-03 18:19:51 +000079#include <algorithm>
Chris Lattner53e677a2004-04-02 20:23:17 +000080using namespace llvm;
81
82namespace {
Chris Lattner5d8925c2006-08-27 22:30:17 +000083 RegisterPass<ScalarEvolution>
Chris Lattner45a1cf82004-04-19 03:42:32 +000084 R("scalar-evolution", "Scalar Evolution Analysis");
Chris Lattner53e677a2004-04-02 20:23:17 +000085
86 Statistic<>
87 NumBruteForceEvaluations("scalar-evolution",
Chris Lattner673e02b2004-10-12 01:49:27 +000088 "Number of brute force evaluations needed to "
89 "calculate high-order polynomial exit values");
90 Statistic<>
91 NumArrayLenItCounts("scalar-evolution",
92 "Number of trip counts computed with array length");
Chris Lattner53e677a2004-04-02 20:23:17 +000093 Statistic<>
94 NumTripCountsComputed("scalar-evolution",
95 "Number of loops with predictable loop counts");
96 Statistic<>
97 NumTripCountsNotComputed("scalar-evolution",
98 "Number of loops without predictable loop counts");
Chris Lattner7980fb92004-04-17 18:36:24 +000099 Statistic<>
100 NumBruteForceTripCountsComputed("scalar-evolution",
101 "Number of loops with trip counts computed by force");
102
103 cl::opt<unsigned>
104 MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden,
Chris Lattnerbed21de2005-09-28 22:30:58 +0000105 cl::desc("Maximum number of iterations SCEV will "
106 "symbolically execute a constant derived loop"),
Chris Lattner7980fb92004-04-17 18:36:24 +0000107 cl::init(100));
Chris Lattner53e677a2004-04-02 20:23:17 +0000108}
109
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 {
119 print(std::cerr);
120}
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();
126 assert(Ty->isInteger() && "Can't get range for a non-integer SCEV!");
127 Ty = Ty->getUnsignedVersion();
128 // Default to a full range if no better information is available.
129 return ConstantRange(getType());
130}
131
132
133SCEVCouldNotCompute::SCEVCouldNotCompute() : SCEV(scCouldNotCompute) {}
134
135bool SCEVCouldNotCompute::isLoopInvariant(const Loop *L) const {
136 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
Misha Brukmanbb2aff12004-04-05 19:00:46 +0000137 return false;
Chris Lattner53e677a2004-04-02 20:23:17 +0000138}
139
140const Type *SCEVCouldNotCompute::getType() const {
141 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
Misha Brukmanbb2aff12004-04-05 19:00:46 +0000142 return 0;
Chris Lattner53e677a2004-04-02 20:23:17 +0000143}
144
145bool SCEVCouldNotCompute::hasComputableLoopEvolution(const Loop *L) const {
146 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
147 return false;
148}
149
Chris Lattner4dc534c2005-02-13 04:37:18 +0000150SCEVHandle SCEVCouldNotCompute::
151replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
152 const SCEVHandle &Conc) const {
153 return this;
154}
155
Chris Lattner53e677a2004-04-02 20:23:17 +0000156void SCEVCouldNotCompute::print(std::ostream &OS) const {
157 OS << "***COULDNOTCOMPUTE***";
158}
159
160bool SCEVCouldNotCompute::classof(const SCEV *S) {
161 return S->getSCEVType() == scCouldNotCompute;
162}
163
164
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000165// SCEVConstants - Only allow the creation of one SCEVConstant for any
166// particular value. Don't use a SCEVHandle here, or else the object will
167// never be deleted!
Chris Lattnerb3364092006-10-04 21:49:37 +0000168static ManagedStatic<std::map<ConstantInt*, SCEVConstant*> > SCEVConstants;
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000169
Chris Lattner53e677a2004-04-02 20:23:17 +0000170
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000171SCEVConstant::~SCEVConstant() {
Chris Lattnerb3364092006-10-04 21:49:37 +0000172 SCEVConstants->erase(V);
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000173}
Chris Lattner53e677a2004-04-02 20:23:17 +0000174
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000175SCEVHandle SCEVConstant::get(ConstantInt *V) {
176 // Make sure that SCEVConstant instances are all unsigned.
177 if (V->getType()->isSigned()) {
178 const Type *NewTy = V->getType()->getUnsignedVersion();
Reid Spencerb83eb642006-10-20 07:07:24 +0000179 V = cast<ConstantInt>(ConstantExpr::getCast(V, NewTy));
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000180 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000181
Chris Lattnerb3364092006-10-04 21:49:37 +0000182 SCEVConstant *&R = (*SCEVConstants)[V];
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000183 if (R == 0) R = new SCEVConstant(V);
184 return R;
185}
Chris Lattner53e677a2004-04-02 20:23:17 +0000186
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000187ConstantRange SCEVConstant::getValueRange() const {
188 return ConstantRange(V);
189}
Chris Lattner53e677a2004-04-02 20:23:17 +0000190
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000191const Type *SCEVConstant::getType() const { return V->getType(); }
Chris Lattner53e677a2004-04-02 20:23:17 +0000192
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000193void SCEVConstant::print(std::ostream &OS) const {
194 WriteAsOperand(OS, V, false);
195}
Chris Lattner53e677a2004-04-02 20:23:17 +0000196
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000197// SCEVTruncates - Only allow the creation of one SCEVTruncateExpr for any
198// particular input. Don't use a SCEVHandle here, or else the object will
199// never be deleted!
Chris Lattnerb3364092006-10-04 21:49:37 +0000200static ManagedStatic<std::map<std::pair<SCEV*, const Type*>,
201 SCEVTruncateExpr*> > SCEVTruncates;
Chris Lattner53e677a2004-04-02 20:23:17 +0000202
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000203SCEVTruncateExpr::SCEVTruncateExpr(const SCEVHandle &op, const Type *ty)
204 : SCEV(scTruncate), Op(op), Ty(ty) {
205 assert(Op->getType()->isInteger() && Ty->isInteger() &&
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000206 "Cannot truncate non-integer value!");
207 assert(Op->getType()->getPrimitiveSize() > Ty->getPrimitiveSize() &&
208 "This is not a truncating conversion!");
209}
Chris Lattner53e677a2004-04-02 20:23:17 +0000210
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000211SCEVTruncateExpr::~SCEVTruncateExpr() {
Chris Lattnerb3364092006-10-04 21:49:37 +0000212 SCEVTruncates->erase(std::make_pair(Op, Ty));
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000213}
Chris Lattner53e677a2004-04-02 20:23:17 +0000214
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000215ConstantRange SCEVTruncateExpr::getValueRange() const {
216 return getOperand()->getValueRange().truncate(getType());
217}
Chris Lattner53e677a2004-04-02 20:23:17 +0000218
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000219void SCEVTruncateExpr::print(std::ostream &OS) const {
220 OS << "(truncate " << *Op << " to " << *Ty << ")";
221}
222
223// SCEVZeroExtends - Only allow the creation of one SCEVZeroExtendExpr for any
224// particular input. Don't use a SCEVHandle here, or else the object will never
225// be deleted!
Chris Lattnerb3364092006-10-04 21:49:37 +0000226static ManagedStatic<std::map<std::pair<SCEV*, const Type*>,
227 SCEVZeroExtendExpr*> > SCEVZeroExtends;
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000228
229SCEVZeroExtendExpr::SCEVZeroExtendExpr(const SCEVHandle &op, const Type *ty)
Reid Spencer48d8a702006-11-01 21:53:12 +0000230 : SCEV(scZeroExtend), Op(op), Ty(ty) {
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000231 assert(Op->getType()->isInteger() && Ty->isInteger() &&
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000232 "Cannot zero extend non-integer value!");
233 assert(Op->getType()->getPrimitiveSize() < Ty->getPrimitiveSize() &&
234 "This is not an extending conversion!");
235}
236
237SCEVZeroExtendExpr::~SCEVZeroExtendExpr() {
Chris Lattnerb3364092006-10-04 21:49:37 +0000238 SCEVZeroExtends->erase(std::make_pair(Op, Ty));
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000239}
240
241ConstantRange SCEVZeroExtendExpr::getValueRange() const {
242 return getOperand()->getValueRange().zeroExtend(getType());
243}
244
245void SCEVZeroExtendExpr::print(std::ostream &OS) const {
246 OS << "(zeroextend " << *Op << " to " << *Ty << ")";
247}
248
249// SCEVCommExprs - Only allow the creation of one SCEVCommutativeExpr for any
250// particular input. Don't use a SCEVHandle here, or else the object will never
251// be deleted!
Chris Lattnerb3364092006-10-04 21:49:37 +0000252static ManagedStatic<std::map<std::pair<unsigned, std::vector<SCEV*> >,
253 SCEVCommutativeExpr*> > SCEVCommExprs;
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000254
255SCEVCommutativeExpr::~SCEVCommutativeExpr() {
Chris Lattnerb3364092006-10-04 21:49:37 +0000256 SCEVCommExprs->erase(std::make_pair(getSCEVType(),
257 std::vector<SCEV*>(Operands.begin(),
258 Operands.end())));
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000259}
260
261void SCEVCommutativeExpr::print(std::ostream &OS) const {
262 assert(Operands.size() > 1 && "This plus expr shouldn't exist!");
263 const char *OpStr = getOperationStr();
264 OS << "(" << *Operands[0];
265 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
266 OS << OpStr << *Operands[i];
267 OS << ")";
268}
269
Chris Lattner4dc534c2005-02-13 04:37:18 +0000270SCEVHandle SCEVCommutativeExpr::
271replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
272 const SCEVHandle &Conc) const {
273 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
274 SCEVHandle H = getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc);
275 if (H != getOperand(i)) {
276 std::vector<SCEVHandle> NewOps;
277 NewOps.reserve(getNumOperands());
278 for (unsigned j = 0; j != i; ++j)
279 NewOps.push_back(getOperand(j));
280 NewOps.push_back(H);
281 for (++i; i != e; ++i)
282 NewOps.push_back(getOperand(i)->
283 replaceSymbolicValuesWithConcrete(Sym, Conc));
284
285 if (isa<SCEVAddExpr>(this))
286 return SCEVAddExpr::get(NewOps);
287 else if (isa<SCEVMulExpr>(this))
288 return SCEVMulExpr::get(NewOps);
289 else
290 assert(0 && "Unknown commutative expr!");
291 }
292 }
293 return this;
294}
295
296
Chris Lattner60a05cc2006-04-01 04:48:52 +0000297// SCEVSDivs - Only allow the creation of one SCEVSDivExpr for any particular
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000298// input. Don't use a SCEVHandle here, or else the object will never be
299// deleted!
Chris Lattnerb3364092006-10-04 21:49:37 +0000300static ManagedStatic<std::map<std::pair<SCEV*, SCEV*>,
301 SCEVSDivExpr*> > SCEVSDivs;
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000302
Chris Lattner60a05cc2006-04-01 04:48:52 +0000303SCEVSDivExpr::~SCEVSDivExpr() {
Chris Lattnerb3364092006-10-04 21:49:37 +0000304 SCEVSDivs->erase(std::make_pair(LHS, RHS));
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000305}
306
Chris Lattner60a05cc2006-04-01 04:48:52 +0000307void SCEVSDivExpr::print(std::ostream &OS) const {
308 OS << "(" << *LHS << " /s " << *RHS << ")";
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000309}
310
Chris Lattner60a05cc2006-04-01 04:48:52 +0000311const Type *SCEVSDivExpr::getType() const {
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000312 const Type *Ty = LHS->getType();
Chris Lattner60a05cc2006-04-01 04:48:52 +0000313 if (Ty->isUnsigned()) Ty = Ty->getSignedVersion();
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000314 return Ty;
315}
316
317// SCEVAddRecExprs - Only allow the creation of one SCEVAddRecExpr for any
318// particular input. Don't use a SCEVHandle here, or else the object will never
319// be deleted!
Chris Lattnerb3364092006-10-04 21:49:37 +0000320static ManagedStatic<std::map<std::pair<const Loop *, std::vector<SCEV*> >,
321 SCEVAddRecExpr*> > SCEVAddRecExprs;
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000322
323SCEVAddRecExpr::~SCEVAddRecExpr() {
Chris Lattnerb3364092006-10-04 21:49:37 +0000324 SCEVAddRecExprs->erase(std::make_pair(L,
325 std::vector<SCEV*>(Operands.begin(),
326 Operands.end())));
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000327}
328
Chris Lattner4dc534c2005-02-13 04:37:18 +0000329SCEVHandle SCEVAddRecExpr::
330replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
331 const SCEVHandle &Conc) const {
332 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
333 SCEVHandle H = getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc);
334 if (H != getOperand(i)) {
335 std::vector<SCEVHandle> NewOps;
336 NewOps.reserve(getNumOperands());
337 for (unsigned j = 0; j != i; ++j)
338 NewOps.push_back(getOperand(j));
339 NewOps.push_back(H);
340 for (++i; i != e; ++i)
341 NewOps.push_back(getOperand(i)->
342 replaceSymbolicValuesWithConcrete(Sym, Conc));
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000343
Chris Lattner4dc534c2005-02-13 04:37:18 +0000344 return get(NewOps, L);
345 }
346 }
347 return this;
348}
349
350
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000351bool SCEVAddRecExpr::isLoopInvariant(const Loop *QueryLoop) const {
352 // This recurrence is invariant w.r.t to QueryLoop iff QueryLoop doesn't
Chris Lattnerff2006a2005-08-16 00:37:01 +0000353 // contain L and if the start is invariant.
354 return !QueryLoop->contains(L->getHeader()) &&
355 getOperand(0)->isLoopInvariant(QueryLoop);
Chris Lattner53e677a2004-04-02 20:23:17 +0000356}
357
358
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000359void SCEVAddRecExpr::print(std::ostream &OS) const {
360 OS << "{" << *Operands[0];
361 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
362 OS << ",+," << *Operands[i];
363 OS << "}<" << L->getHeader()->getName() + ">";
364}
Chris Lattner53e677a2004-04-02 20:23:17 +0000365
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000366// SCEVUnknowns - Only allow the creation of one SCEVUnknown for any particular
367// value. Don't use a SCEVHandle here, or else the object will never be
368// deleted!
Chris Lattnerb3364092006-10-04 21:49:37 +0000369static ManagedStatic<std::map<Value*, SCEVUnknown*> > SCEVUnknowns;
Chris Lattner53e677a2004-04-02 20:23:17 +0000370
Chris Lattnerb3364092006-10-04 21:49:37 +0000371SCEVUnknown::~SCEVUnknown() { SCEVUnknowns->erase(V); }
Chris Lattner53e677a2004-04-02 20:23:17 +0000372
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000373bool SCEVUnknown::isLoopInvariant(const Loop *L) const {
374 // All non-instruction values are loop invariant. All instructions are loop
375 // invariant if they are not contained in the specified loop.
376 if (Instruction *I = dyn_cast<Instruction>(V))
377 return !L->contains(I->getParent());
378 return true;
379}
Chris Lattner53e677a2004-04-02 20:23:17 +0000380
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000381const Type *SCEVUnknown::getType() const {
382 return V->getType();
383}
Chris Lattner53e677a2004-04-02 20:23:17 +0000384
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000385void SCEVUnknown::print(std::ostream &OS) const {
386 WriteAsOperand(OS, V, false);
Chris Lattner53e677a2004-04-02 20:23:17 +0000387}
388
Chris Lattner8d741b82004-06-20 06:23:15 +0000389//===----------------------------------------------------------------------===//
390// SCEV Utilities
391//===----------------------------------------------------------------------===//
392
393namespace {
394 /// SCEVComplexityCompare - Return true if the complexity of the LHS is less
395 /// than the complexity of the RHS. This comparator is used to canonicalize
396 /// expressions.
Chris Lattner95255282006-06-28 23:17:24 +0000397 struct VISIBILITY_HIDDEN SCEVComplexityCompare {
Chris Lattner8d741b82004-06-20 06:23:15 +0000398 bool operator()(SCEV *LHS, SCEV *RHS) {
399 return LHS->getSCEVType() < RHS->getSCEVType();
400 }
401 };
402}
403
404/// GroupByComplexity - Given a list of SCEV objects, order them by their
405/// complexity, and group objects of the same complexity together by value.
406/// When this routine is finished, we know that any duplicates in the vector are
407/// consecutive and that complexity is monotonically increasing.
408///
409/// Note that we go take special precautions to ensure that we get determinstic
410/// results from this routine. In other words, we don't want the results of
411/// this to depend on where the addresses of various SCEV objects happened to
412/// land in memory.
413///
414static void GroupByComplexity(std::vector<SCEVHandle> &Ops) {
415 if (Ops.size() < 2) return; // Noop
416 if (Ops.size() == 2) {
417 // This is the common case, which also happens to be trivially simple.
418 // Special case it.
419 if (Ops[0]->getSCEVType() > Ops[1]->getSCEVType())
420 std::swap(Ops[0], Ops[1]);
421 return;
422 }
423
424 // Do the rough sort by complexity.
425 std::sort(Ops.begin(), Ops.end(), SCEVComplexityCompare());
426
427 // Now that we are sorted by complexity, group elements of the same
428 // complexity. Note that this is, at worst, N^2, but the vector is likely to
429 // be extremely short in practice. Note that we take this approach because we
430 // do not want to depend on the addresses of the objects we are grouping.
Chris Lattner2d584522004-06-20 17:01:44 +0000431 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
Chris Lattner8d741b82004-06-20 06:23:15 +0000432 SCEV *S = Ops[i];
433 unsigned Complexity = S->getSCEVType();
434
435 // If there are any objects of the same complexity and same value as this
436 // one, group them.
437 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
438 if (Ops[j] == S) { // Found a duplicate.
439 // Move it to immediately after i'th element.
440 std::swap(Ops[i+1], Ops[j]);
441 ++i; // no need to rescan it.
Chris Lattner541ad5e2004-06-20 20:32:16 +0000442 if (i == e-2) return; // Done!
Chris Lattner8d741b82004-06-20 06:23:15 +0000443 }
444 }
445 }
446}
447
Chris Lattner53e677a2004-04-02 20:23:17 +0000448
Chris Lattner53e677a2004-04-02 20:23:17 +0000449
450//===----------------------------------------------------------------------===//
451// Simple SCEV method implementations
452//===----------------------------------------------------------------------===//
453
454/// getIntegerSCEV - Given an integer or FP type, create a constant for the
455/// specified signed integer value and return a SCEV for the constant.
Chris Lattnerb06432c2004-04-23 21:29:03 +0000456SCEVHandle SCEVUnknown::getIntegerSCEV(int Val, const Type *Ty) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000457 Constant *C;
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000458 if (Val == 0)
Chris Lattner53e677a2004-04-02 20:23:17 +0000459 C = Constant::getNullValue(Ty);
460 else if (Ty->isFloatingPoint())
461 C = ConstantFP::get(Ty, Val);
462 else if (Ty->isSigned())
Reid Spencerb83eb642006-10-20 07:07:24 +0000463 C = ConstantInt::get(Ty, Val);
Chris Lattner53e677a2004-04-02 20:23:17 +0000464 else {
Reid Spencerb83eb642006-10-20 07:07:24 +0000465 C = ConstantInt::get(Ty->getSignedVersion(), Val);
Chris Lattner53e677a2004-04-02 20:23:17 +0000466 C = ConstantExpr::getCast(C, Ty);
467 }
468 return SCEVUnknown::get(C);
469}
470
471/// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion of the
472/// input value to the specified type. If the type must be extended, it is zero
473/// extended.
474static SCEVHandle getTruncateOrZeroExtend(const SCEVHandle &V, const Type *Ty) {
475 const Type *SrcTy = V->getType();
476 assert(SrcTy->isInteger() && Ty->isInteger() &&
477 "Cannot truncate or zero extend with non-integer arguments!");
478 if (SrcTy->getPrimitiveSize() == Ty->getPrimitiveSize())
479 return V; // No conversion
480 if (SrcTy->getPrimitiveSize() > Ty->getPrimitiveSize())
481 return SCEVTruncateExpr::get(V, Ty);
482 return SCEVZeroExtendExpr::get(V, Ty);
483}
484
485/// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V
486///
Chris Lattnerbac5b462005-03-09 05:34:41 +0000487SCEVHandle SCEV::getNegativeSCEV(const SCEVHandle &V) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000488 if (SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
489 return SCEVUnknown::get(ConstantExpr::getNeg(VC->getValue()));
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000490
Chris Lattnerb06432c2004-04-23 21:29:03 +0000491 return SCEVMulExpr::get(V, SCEVUnknown::getIntegerSCEV(-1, V->getType()));
Chris Lattner53e677a2004-04-02 20:23:17 +0000492}
493
494/// getMinusSCEV - Return a SCEV corresponding to LHS - RHS.
495///
Chris Lattnerbac5b462005-03-09 05:34:41 +0000496SCEVHandle SCEV::getMinusSCEV(const SCEVHandle &LHS, const SCEVHandle &RHS) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000497 // X - Y --> X + -Y
Chris Lattnerbac5b462005-03-09 05:34:41 +0000498 return SCEVAddExpr::get(LHS, SCEV::getNegativeSCEV(RHS));
Chris Lattner53e677a2004-04-02 20:23:17 +0000499}
500
501
Chris Lattner53e677a2004-04-02 20:23:17 +0000502/// PartialFact - Compute V!/(V-NumSteps)!
503static SCEVHandle PartialFact(SCEVHandle V, unsigned NumSteps) {
504 // Handle this case efficiently, it is common to have constant iteration
505 // counts while computing loop exit values.
506 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(V)) {
Reid Spencerb83eb642006-10-20 07:07:24 +0000507 uint64_t Val = SC->getValue()->getZExtValue();
Chris Lattner53e677a2004-04-02 20:23:17 +0000508 uint64_t Result = 1;
509 for (; NumSteps; --NumSteps)
510 Result *= Val-(NumSteps-1);
Reid Spencerb83eb642006-10-20 07:07:24 +0000511 Constant *Res = ConstantInt::get(Type::ULongTy, Result);
Chris Lattner53e677a2004-04-02 20:23:17 +0000512 return SCEVUnknown::get(ConstantExpr::getCast(Res, V->getType()));
513 }
514
515 const Type *Ty = V->getType();
516 if (NumSteps == 0)
Chris Lattnerb06432c2004-04-23 21:29:03 +0000517 return SCEVUnknown::getIntegerSCEV(1, Ty);
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000518
Chris Lattner53e677a2004-04-02 20:23:17 +0000519 SCEVHandle Result = V;
520 for (unsigned i = 1; i != NumSteps; ++i)
Chris Lattnerbac5b462005-03-09 05:34:41 +0000521 Result = SCEVMulExpr::get(Result, SCEV::getMinusSCEV(V,
Chris Lattnerb06432c2004-04-23 21:29:03 +0000522 SCEVUnknown::getIntegerSCEV(i, Ty)));
Chris Lattner53e677a2004-04-02 20:23:17 +0000523 return Result;
524}
525
526
527/// evaluateAtIteration - Return the value of this chain of recurrences at
528/// the specified iteration number. We can evaluate this recurrence by
529/// multiplying each element in the chain by the binomial coefficient
530/// corresponding to it. In other words, we can evaluate {A,+,B,+,C,+,D} as:
531///
532/// A*choose(It, 0) + B*choose(It, 1) + C*choose(It, 2) + D*choose(It, 3)
533///
534/// FIXME/VERIFY: I don't trust that this is correct in the face of overflow.
535/// Is the binomial equation safe using modular arithmetic??
536///
537SCEVHandle SCEVAddRecExpr::evaluateAtIteration(SCEVHandle It) const {
538 SCEVHandle Result = getStart();
539 int Divisor = 1;
540 const Type *Ty = It->getType();
541 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
542 SCEVHandle BC = PartialFact(It, i);
543 Divisor *= i;
Chris Lattner60a05cc2006-04-01 04:48:52 +0000544 SCEVHandle Val = SCEVSDivExpr::get(SCEVMulExpr::get(BC, getOperand(i)),
Chris Lattnerb06432c2004-04-23 21:29:03 +0000545 SCEVUnknown::getIntegerSCEV(Divisor,Ty));
Chris Lattner53e677a2004-04-02 20:23:17 +0000546 Result = SCEVAddExpr::get(Result, Val);
547 }
548 return Result;
549}
550
551
552//===----------------------------------------------------------------------===//
553// SCEV Expression folder implementations
554//===----------------------------------------------------------------------===//
555
556SCEVHandle SCEVTruncateExpr::get(const SCEVHandle &Op, const Type *Ty) {
557 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
558 return SCEVUnknown::get(ConstantExpr::getCast(SC->getValue(), Ty));
559
560 // If the input value is a chrec scev made out of constants, truncate
561 // all of the constants.
562 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
563 std::vector<SCEVHandle> Operands;
564 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
565 // FIXME: This should allow truncation of other expression types!
566 if (isa<SCEVConstant>(AddRec->getOperand(i)))
567 Operands.push_back(get(AddRec->getOperand(i), Ty));
568 else
569 break;
570 if (Operands.size() == AddRec->getNumOperands())
571 return SCEVAddRecExpr::get(Operands, AddRec->getLoop());
572 }
573
Chris Lattnerb3364092006-10-04 21:49:37 +0000574 SCEVTruncateExpr *&Result = (*SCEVTruncates)[std::make_pair(Op, Ty)];
Chris Lattner53e677a2004-04-02 20:23:17 +0000575 if (Result == 0) Result = new SCEVTruncateExpr(Op, Ty);
576 return Result;
577}
578
579SCEVHandle SCEVZeroExtendExpr::get(const SCEVHandle &Op, const Type *Ty) {
580 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
581 return SCEVUnknown::get(ConstantExpr::getCast(SC->getValue(), Ty));
582
583 // FIXME: If the input value is a chrec scev, and we can prove that the value
584 // did not overflow the old, smaller, value, we can zero extend all of the
585 // operands (often constants). This would allow analysis of something like
586 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
587
Chris Lattnerb3364092006-10-04 21:49:37 +0000588 SCEVZeroExtendExpr *&Result = (*SCEVZeroExtends)[std::make_pair(Op, Ty)];
Chris Lattner53e677a2004-04-02 20:23:17 +0000589 if (Result == 0) Result = new SCEVZeroExtendExpr(Op, Ty);
590 return Result;
591}
592
593// get - Get a canonical add expression, or something simpler if possible.
594SCEVHandle SCEVAddExpr::get(std::vector<SCEVHandle> &Ops) {
595 assert(!Ops.empty() && "Cannot get empty add!");
Chris Lattner627018b2004-04-07 16:16:11 +0000596 if (Ops.size() == 1) return Ops[0];
Chris Lattner53e677a2004-04-02 20:23:17 +0000597
598 // Sort by complexity, this groups all similar expression types together.
Chris Lattner8d741b82004-06-20 06:23:15 +0000599 GroupByComplexity(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +0000600
601 // If there are any constants, fold them together.
602 unsigned Idx = 0;
603 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
604 ++Idx;
Chris Lattner627018b2004-04-07 16:16:11 +0000605 assert(Idx < Ops.size());
Chris Lattner53e677a2004-04-02 20:23:17 +0000606 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
607 // We found two constants, fold them together!
608 Constant *Fold = ConstantExpr::getAdd(LHSC->getValue(), RHSC->getValue());
609 if (ConstantInt *CI = dyn_cast<ConstantInt>(Fold)) {
610 Ops[0] = SCEVConstant::get(CI);
611 Ops.erase(Ops.begin()+1); // Erase the folded element
612 if (Ops.size() == 1) return Ops[0];
Chris Lattner7ffc07d2005-02-26 18:50:19 +0000613 LHSC = cast<SCEVConstant>(Ops[0]);
Chris Lattner53e677a2004-04-02 20:23:17 +0000614 } else {
615 // If we couldn't fold the expression, move to the next constant. Note
616 // that this is impossible to happen in practice because we always
617 // constant fold constant ints to constant ints.
618 ++Idx;
619 }
620 }
621
622 // If we are left with a constant zero being added, strip it off.
623 if (cast<SCEVConstant>(Ops[0])->getValue()->isNullValue()) {
624 Ops.erase(Ops.begin());
625 --Idx;
626 }
627 }
628
Chris Lattner627018b2004-04-07 16:16:11 +0000629 if (Ops.size() == 1) return Ops[0];
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000630
Chris Lattner53e677a2004-04-02 20:23:17 +0000631 // Okay, check to see if the same value occurs in the operand list twice. If
632 // so, merge them together into an multiply expression. Since we sorted the
633 // list, these values are required to be adjacent.
634 const Type *Ty = Ops[0]->getType();
635 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
636 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
637 // Found a match, merge the two values into a multiply, and add any
638 // remaining values to the result.
Chris Lattnerb06432c2004-04-23 21:29:03 +0000639 SCEVHandle Two = SCEVUnknown::getIntegerSCEV(2, Ty);
Chris Lattner53e677a2004-04-02 20:23:17 +0000640 SCEVHandle Mul = SCEVMulExpr::get(Ops[i], Two);
641 if (Ops.size() == 2)
642 return Mul;
643 Ops.erase(Ops.begin()+i, Ops.begin()+i+2);
644 Ops.push_back(Mul);
645 return SCEVAddExpr::get(Ops);
646 }
647
648 // Okay, now we know the first non-constant operand. If there are add
649 // operands they would be next.
650 if (Idx < Ops.size()) {
651 bool DeletedAdd = false;
652 while (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
653 // If we have an add, expand the add operands onto the end of the operands
654 // list.
655 Ops.insert(Ops.end(), Add->op_begin(), Add->op_end());
656 Ops.erase(Ops.begin()+Idx);
657 DeletedAdd = true;
658 }
659
660 // If we deleted at least one add, we added operands to the end of the list,
661 // and they are not necessarily sorted. Recurse to resort and resimplify
662 // any operands we just aquired.
663 if (DeletedAdd)
664 return get(Ops);
665 }
666
667 // Skip over the add expression until we get to a multiply.
668 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
669 ++Idx;
670
671 // If we are adding something to a multiply expression, make sure the
672 // something is not already an operand of the multiply. If so, merge it into
673 // the multiply.
674 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
675 SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
676 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
677 SCEV *MulOpSCEV = Mul->getOperand(MulOp);
678 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
Chris Lattner6a1a78a2004-12-04 20:54:32 +0000679 if (MulOpSCEV == Ops[AddOp] && !isa<SCEVConstant>(MulOpSCEV)) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000680 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
681 SCEVHandle InnerMul = Mul->getOperand(MulOp == 0);
682 if (Mul->getNumOperands() != 2) {
683 // If the multiply has more than two operands, we must get the
684 // Y*Z term.
685 std::vector<SCEVHandle> MulOps(Mul->op_begin(), Mul->op_end());
686 MulOps.erase(MulOps.begin()+MulOp);
687 InnerMul = SCEVMulExpr::get(MulOps);
688 }
Chris Lattnerb06432c2004-04-23 21:29:03 +0000689 SCEVHandle One = SCEVUnknown::getIntegerSCEV(1, Ty);
Chris Lattner53e677a2004-04-02 20:23:17 +0000690 SCEVHandle AddOne = SCEVAddExpr::get(InnerMul, One);
691 SCEVHandle OuterMul = SCEVMulExpr::get(AddOne, Ops[AddOp]);
692 if (Ops.size() == 2) return OuterMul;
693 if (AddOp < Idx) {
694 Ops.erase(Ops.begin()+AddOp);
695 Ops.erase(Ops.begin()+Idx-1);
696 } else {
697 Ops.erase(Ops.begin()+Idx);
698 Ops.erase(Ops.begin()+AddOp-1);
699 }
700 Ops.push_back(OuterMul);
701 return SCEVAddExpr::get(Ops);
702 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000703
Chris Lattner53e677a2004-04-02 20:23:17 +0000704 // Check this multiply against other multiplies being added together.
705 for (unsigned OtherMulIdx = Idx+1;
706 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
707 ++OtherMulIdx) {
708 SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
709 // If MulOp occurs in OtherMul, we can fold the two multiplies
710 // together.
711 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
712 OMulOp != e; ++OMulOp)
713 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
714 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
715 SCEVHandle InnerMul1 = Mul->getOperand(MulOp == 0);
716 if (Mul->getNumOperands() != 2) {
717 std::vector<SCEVHandle> MulOps(Mul->op_begin(), Mul->op_end());
718 MulOps.erase(MulOps.begin()+MulOp);
719 InnerMul1 = SCEVMulExpr::get(MulOps);
720 }
721 SCEVHandle InnerMul2 = OtherMul->getOperand(OMulOp == 0);
722 if (OtherMul->getNumOperands() != 2) {
723 std::vector<SCEVHandle> MulOps(OtherMul->op_begin(),
724 OtherMul->op_end());
725 MulOps.erase(MulOps.begin()+OMulOp);
726 InnerMul2 = SCEVMulExpr::get(MulOps);
727 }
728 SCEVHandle InnerMulSum = SCEVAddExpr::get(InnerMul1,InnerMul2);
729 SCEVHandle OuterMul = SCEVMulExpr::get(MulOpSCEV, InnerMulSum);
730 if (Ops.size() == 2) return OuterMul;
731 Ops.erase(Ops.begin()+Idx);
732 Ops.erase(Ops.begin()+OtherMulIdx-1);
733 Ops.push_back(OuterMul);
734 return SCEVAddExpr::get(Ops);
735 }
736 }
737 }
738 }
739
740 // If there are any add recurrences in the operands list, see if any other
741 // added values are loop invariant. If so, we can fold them into the
742 // recurrence.
743 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
744 ++Idx;
745
746 // Scan over all recurrences, trying to fold loop invariants into them.
747 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
748 // Scan all of the other operands to this add and add them to the vector if
749 // they are loop invariant w.r.t. the recurrence.
750 std::vector<SCEVHandle> LIOps;
751 SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
752 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
753 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
754 LIOps.push_back(Ops[i]);
755 Ops.erase(Ops.begin()+i);
756 --i; --e;
757 }
758
759 // If we found some loop invariants, fold them into the recurrence.
760 if (!LIOps.empty()) {
761 // NLI + LI + { Start,+,Step} --> NLI + { LI+Start,+,Step }
762 LIOps.push_back(AddRec->getStart());
763
764 std::vector<SCEVHandle> AddRecOps(AddRec->op_begin(), AddRec->op_end());
765 AddRecOps[0] = SCEVAddExpr::get(LIOps);
766
767 SCEVHandle NewRec = SCEVAddRecExpr::get(AddRecOps, AddRec->getLoop());
768 // If all of the other operands were loop invariant, we are done.
769 if (Ops.size() == 1) return NewRec;
770
771 // Otherwise, add the folded AddRec by the non-liv parts.
772 for (unsigned i = 0;; ++i)
773 if (Ops[i] == AddRec) {
774 Ops[i] = NewRec;
775 break;
776 }
777 return SCEVAddExpr::get(Ops);
778 }
779
780 // Okay, if there weren't any loop invariants to be folded, check to see if
781 // there are multiple AddRec's with the same loop induction variable being
782 // added together. If so, we can fold them.
783 for (unsigned OtherIdx = Idx+1;
784 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
785 if (OtherIdx != Idx) {
786 SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
787 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
788 // Other + {A,+,B} + {C,+,D} --> Other + {A+C,+,B+D}
789 std::vector<SCEVHandle> NewOps(AddRec->op_begin(), AddRec->op_end());
790 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); i != e; ++i) {
791 if (i >= NewOps.size()) {
792 NewOps.insert(NewOps.end(), OtherAddRec->op_begin()+i,
793 OtherAddRec->op_end());
794 break;
795 }
796 NewOps[i] = SCEVAddExpr::get(NewOps[i], OtherAddRec->getOperand(i));
797 }
798 SCEVHandle NewAddRec = SCEVAddRecExpr::get(NewOps, AddRec->getLoop());
799
800 if (Ops.size() == 2) return NewAddRec;
801
802 Ops.erase(Ops.begin()+Idx);
803 Ops.erase(Ops.begin()+OtherIdx-1);
804 Ops.push_back(NewAddRec);
805 return SCEVAddExpr::get(Ops);
806 }
807 }
808
809 // Otherwise couldn't fold anything into this recurrence. Move onto the
810 // next one.
811 }
812
813 // Okay, it looks like we really DO need an add expr. Check to see if we
814 // already have one, otherwise create a new one.
815 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
Chris Lattnerb3364092006-10-04 21:49:37 +0000816 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scAddExpr,
817 SCEVOps)];
Chris Lattner53e677a2004-04-02 20:23:17 +0000818 if (Result == 0) Result = new SCEVAddExpr(Ops);
819 return Result;
820}
821
822
823SCEVHandle SCEVMulExpr::get(std::vector<SCEVHandle> &Ops) {
824 assert(!Ops.empty() && "Cannot get empty mul!");
825
826 // Sort by complexity, this groups all similar expression types together.
Chris Lattner8d741b82004-06-20 06:23:15 +0000827 GroupByComplexity(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +0000828
829 // If there are any constants, fold them together.
830 unsigned Idx = 0;
831 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
832
833 // C1*(C2+V) -> C1*C2 + C1*V
834 if (Ops.size() == 2)
835 if (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
836 if (Add->getNumOperands() == 2 &&
837 isa<SCEVConstant>(Add->getOperand(0)))
838 return SCEVAddExpr::get(SCEVMulExpr::get(LHSC, Add->getOperand(0)),
839 SCEVMulExpr::get(LHSC, Add->getOperand(1)));
840
841
842 ++Idx;
843 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
844 // We found two constants, fold them together!
845 Constant *Fold = ConstantExpr::getMul(LHSC->getValue(), RHSC->getValue());
846 if (ConstantInt *CI = dyn_cast<ConstantInt>(Fold)) {
847 Ops[0] = SCEVConstant::get(CI);
848 Ops.erase(Ops.begin()+1); // Erase the folded element
849 if (Ops.size() == 1) return Ops[0];
Chris Lattner7ffc07d2005-02-26 18:50:19 +0000850 LHSC = cast<SCEVConstant>(Ops[0]);
Chris Lattner53e677a2004-04-02 20:23:17 +0000851 } else {
852 // If we couldn't fold the expression, move to the next constant. Note
853 // that this is impossible to happen in practice because we always
854 // constant fold constant ints to constant ints.
855 ++Idx;
856 }
857 }
858
859 // If we are left with a constant one being multiplied, strip it off.
860 if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) {
861 Ops.erase(Ops.begin());
862 --Idx;
863 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isNullValue()) {
864 // If we have a multiply of zero, it will always be zero.
865 return Ops[0];
866 }
867 }
868
869 // Skip over the add expression until we get to a multiply.
870 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
871 ++Idx;
872
873 if (Ops.size() == 1)
874 return Ops[0];
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000875
Chris Lattner53e677a2004-04-02 20:23:17 +0000876 // If there are mul operands inline them all into this expression.
877 if (Idx < Ops.size()) {
878 bool DeletedMul = false;
879 while (SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
880 // If we have an mul, expand the mul operands onto the end of the operands
881 // list.
882 Ops.insert(Ops.end(), Mul->op_begin(), Mul->op_end());
883 Ops.erase(Ops.begin()+Idx);
884 DeletedMul = true;
885 }
886
887 // If we deleted at least one mul, we added operands to the end of the list,
888 // and they are not necessarily sorted. Recurse to resort and resimplify
889 // any operands we just aquired.
890 if (DeletedMul)
891 return get(Ops);
892 }
893
894 // If there are any add recurrences in the operands list, see if any other
895 // added values are loop invariant. If so, we can fold them into the
896 // recurrence.
897 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
898 ++Idx;
899
900 // Scan over all recurrences, trying to fold loop invariants into them.
901 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
902 // Scan all of the other operands to this mul and add them to the vector if
903 // they are loop invariant w.r.t. the recurrence.
904 std::vector<SCEVHandle> LIOps;
905 SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
906 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
907 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
908 LIOps.push_back(Ops[i]);
909 Ops.erase(Ops.begin()+i);
910 --i; --e;
911 }
912
913 // If we found some loop invariants, fold them into the recurrence.
914 if (!LIOps.empty()) {
915 // NLI * LI * { Start,+,Step} --> NLI * { LI*Start,+,LI*Step }
916 std::vector<SCEVHandle> NewOps;
917 NewOps.reserve(AddRec->getNumOperands());
918 if (LIOps.size() == 1) {
919 SCEV *Scale = LIOps[0];
920 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
921 NewOps.push_back(SCEVMulExpr::get(Scale, AddRec->getOperand(i)));
922 } else {
923 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
924 std::vector<SCEVHandle> MulOps(LIOps);
925 MulOps.push_back(AddRec->getOperand(i));
926 NewOps.push_back(SCEVMulExpr::get(MulOps));
927 }
928 }
929
930 SCEVHandle NewRec = SCEVAddRecExpr::get(NewOps, AddRec->getLoop());
931
932 // If all of the other operands were loop invariant, we are done.
933 if (Ops.size() == 1) return NewRec;
934
935 // Otherwise, multiply the folded AddRec by the non-liv parts.
936 for (unsigned i = 0;; ++i)
937 if (Ops[i] == AddRec) {
938 Ops[i] = NewRec;
939 break;
940 }
941 return SCEVMulExpr::get(Ops);
942 }
943
944 // Okay, if there weren't any loop invariants to be folded, check to see if
945 // there are multiple AddRec's with the same loop induction variable being
946 // multiplied together. If so, we can fold them.
947 for (unsigned OtherIdx = Idx+1;
948 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
949 if (OtherIdx != Idx) {
950 SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
951 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
952 // F * G --> {A,+,B} * {C,+,D} --> {A*C,+,F*D + G*B + B*D}
953 SCEVAddRecExpr *F = AddRec, *G = OtherAddRec;
954 SCEVHandle NewStart = SCEVMulExpr::get(F->getStart(),
955 G->getStart());
956 SCEVHandle B = F->getStepRecurrence();
957 SCEVHandle D = G->getStepRecurrence();
958 SCEVHandle NewStep = SCEVAddExpr::get(SCEVMulExpr::get(F, D),
959 SCEVMulExpr::get(G, B),
960 SCEVMulExpr::get(B, D));
961 SCEVHandle NewAddRec = SCEVAddRecExpr::get(NewStart, NewStep,
962 F->getLoop());
963 if (Ops.size() == 2) return NewAddRec;
964
965 Ops.erase(Ops.begin()+Idx);
966 Ops.erase(Ops.begin()+OtherIdx-1);
967 Ops.push_back(NewAddRec);
968 return SCEVMulExpr::get(Ops);
969 }
970 }
971
972 // Otherwise couldn't fold anything into this recurrence. Move onto the
973 // next one.
974 }
975
976 // Okay, it looks like we really DO need an mul expr. Check to see if we
977 // already have one, otherwise create a new one.
978 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
Chris Lattnerb3364092006-10-04 21:49:37 +0000979 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scMulExpr,
980 SCEVOps)];
Chris Lattner6a1a78a2004-12-04 20:54:32 +0000981 if (Result == 0)
982 Result = new SCEVMulExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +0000983 return Result;
984}
985
Chris Lattner60a05cc2006-04-01 04:48:52 +0000986SCEVHandle SCEVSDivExpr::get(const SCEVHandle &LHS, const SCEVHandle &RHS) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000987 if (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
988 if (RHSC->getValue()->equalsInt(1))
Reid Spencer1628cec2006-10-26 06:15:43 +0000989 return LHS; // X sdiv 1 --> x
Chris Lattner53e677a2004-04-02 20:23:17 +0000990 if (RHSC->getValue()->isAllOnesValue())
Reid Spencer1628cec2006-10-26 06:15:43 +0000991 return SCEV::getNegativeSCEV(LHS); // X sdiv -1 --> -x
Chris Lattner53e677a2004-04-02 20:23:17 +0000992
993 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
994 Constant *LHSCV = LHSC->getValue();
995 Constant *RHSCV = RHSC->getValue();
Chris Lattner60a05cc2006-04-01 04:48:52 +0000996 if (LHSCV->getType()->isUnsigned())
Chris Lattner53e677a2004-04-02 20:23:17 +0000997 LHSCV = ConstantExpr::getCast(LHSCV,
Chris Lattner60a05cc2006-04-01 04:48:52 +0000998 LHSCV->getType()->getSignedVersion());
999 if (RHSCV->getType()->isUnsigned())
Chris Lattner53e677a2004-04-02 20:23:17 +00001000 RHSCV = ConstantExpr::getCast(RHSCV, LHSCV->getType());
Reid Spencer1628cec2006-10-26 06:15:43 +00001001 return SCEVUnknown::get(ConstantExpr::getSDiv(LHSCV, RHSCV));
Chris Lattner53e677a2004-04-02 20:23:17 +00001002 }
1003 }
1004
1005 // FIXME: implement folding of (X*4)/4 when we know X*4 doesn't overflow.
1006
Chris Lattnerb3364092006-10-04 21:49:37 +00001007 SCEVSDivExpr *&Result = (*SCEVSDivs)[std::make_pair(LHS, RHS)];
Chris Lattner60a05cc2006-04-01 04:48:52 +00001008 if (Result == 0) Result = new SCEVSDivExpr(LHS, RHS);
Chris Lattner53e677a2004-04-02 20:23:17 +00001009 return Result;
1010}
1011
1012
1013/// SCEVAddRecExpr::get - Get a add recurrence expression for the
1014/// specified loop. Simplify the expression as much as possible.
1015SCEVHandle SCEVAddRecExpr::get(const SCEVHandle &Start,
1016 const SCEVHandle &Step, const Loop *L) {
1017 std::vector<SCEVHandle> Operands;
1018 Operands.push_back(Start);
1019 if (SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
1020 if (StepChrec->getLoop() == L) {
1021 Operands.insert(Operands.end(), StepChrec->op_begin(),
1022 StepChrec->op_end());
1023 return get(Operands, L);
1024 }
1025
1026 Operands.push_back(Step);
1027 return get(Operands, L);
1028}
1029
1030/// SCEVAddRecExpr::get - Get a add recurrence expression for the
1031/// specified loop. Simplify the expression as much as possible.
1032SCEVHandle SCEVAddRecExpr::get(std::vector<SCEVHandle> &Operands,
1033 const Loop *L) {
1034 if (Operands.size() == 1) return Operands[0];
1035
1036 if (SCEVConstant *StepC = dyn_cast<SCEVConstant>(Operands.back()))
1037 if (StepC->getValue()->isNullValue()) {
1038 Operands.pop_back();
1039 return get(Operands, L); // { X,+,0 } --> X
1040 }
1041
1042 SCEVAddRecExpr *&Result =
Chris Lattnerb3364092006-10-04 21:49:37 +00001043 (*SCEVAddRecExprs)[std::make_pair(L, std::vector<SCEV*>(Operands.begin(),
1044 Operands.end()))];
Chris Lattner53e677a2004-04-02 20:23:17 +00001045 if (Result == 0) Result = new SCEVAddRecExpr(Operands, L);
1046 return Result;
1047}
1048
Chris Lattner0a7f98c2004-04-15 15:07:24 +00001049SCEVHandle SCEVUnknown::get(Value *V) {
1050 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
1051 return SCEVConstant::get(CI);
Chris Lattnerb3364092006-10-04 21:49:37 +00001052 SCEVUnknown *&Result = (*SCEVUnknowns)[V];
Chris Lattner0a7f98c2004-04-15 15:07:24 +00001053 if (Result == 0) Result = new SCEVUnknown(V);
1054 return Result;
1055}
1056
Chris Lattner53e677a2004-04-02 20:23:17 +00001057
1058//===----------------------------------------------------------------------===//
Chris Lattner53e677a2004-04-02 20:23:17 +00001059// ScalarEvolutionsImpl Definition and Implementation
1060//===----------------------------------------------------------------------===//
1061//
1062/// ScalarEvolutionsImpl - This class implements the main driver for the scalar
1063/// evolution code.
1064///
1065namespace {
Chris Lattner95255282006-06-28 23:17:24 +00001066 struct VISIBILITY_HIDDEN ScalarEvolutionsImpl {
Chris Lattner53e677a2004-04-02 20:23:17 +00001067 /// F - The function we are analyzing.
1068 ///
1069 Function &F;
1070
1071 /// LI - The loop information for the function we are currently analyzing.
1072 ///
1073 LoopInfo &LI;
1074
1075 /// UnknownValue - This SCEV is used to represent unknown trip counts and
1076 /// things.
1077 SCEVHandle UnknownValue;
1078
1079 /// Scalars - This is a cache of the scalars we have analyzed so far.
1080 ///
1081 std::map<Value*, SCEVHandle> Scalars;
1082
1083 /// IterationCounts - Cache the iteration count of the loops for this
1084 /// function as they are computed.
1085 std::map<const Loop*, SCEVHandle> IterationCounts;
1086
Chris Lattner3221ad02004-04-17 22:58:41 +00001087 /// ConstantEvolutionLoopExitValue - This map contains entries for all of
1088 /// the PHI instructions that we attempt to compute constant evolutions for.
1089 /// This allows us to avoid potentially expensive recomputation of these
1090 /// properties. An instruction maps to null if we are unable to compute its
1091 /// exit value.
1092 std::map<PHINode*, Constant*> ConstantEvolutionLoopExitValue;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001093
Chris Lattner53e677a2004-04-02 20:23:17 +00001094 public:
1095 ScalarEvolutionsImpl(Function &f, LoopInfo &li)
1096 : F(f), LI(li), UnknownValue(new SCEVCouldNotCompute()) {}
1097
1098 /// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
1099 /// expression and create a new one.
1100 SCEVHandle getSCEV(Value *V);
1101
Chris Lattnera0740fb2005-08-09 23:36:33 +00001102 /// hasSCEV - Return true if the SCEV for this value has already been
1103 /// computed.
1104 bool hasSCEV(Value *V) const {
1105 return Scalars.count(V);
1106 }
1107
1108 /// setSCEV - Insert the specified SCEV into the map of current SCEVs for
1109 /// the specified value.
1110 void setSCEV(Value *V, const SCEVHandle &H) {
1111 bool isNew = Scalars.insert(std::make_pair(V, H)).second;
1112 assert(isNew && "This entry already existed!");
1113 }
1114
1115
Chris Lattner53e677a2004-04-02 20:23:17 +00001116 /// getSCEVAtScope - Compute the value of the specified expression within
1117 /// the indicated loop (which may be null to indicate in no loop). If the
1118 /// expression cannot be evaluated, return UnknownValue itself.
1119 SCEVHandle getSCEVAtScope(SCEV *V, const Loop *L);
1120
1121
1122 /// hasLoopInvariantIterationCount - Return true if the specified loop has
1123 /// an analyzable loop-invariant iteration count.
1124 bool hasLoopInvariantIterationCount(const Loop *L);
1125
1126 /// getIterationCount - If the specified loop has a predictable iteration
1127 /// count, return it. Note that it is not valid to call this method on a
1128 /// loop without a loop-invariant iteration count.
1129 SCEVHandle getIterationCount(const Loop *L);
1130
1131 /// deleteInstructionFromRecords - This method should be called by the
1132 /// client before it removes an instruction from the program, to make sure
1133 /// that no dangling references are left around.
1134 void deleteInstructionFromRecords(Instruction *I);
1135
1136 private:
1137 /// createSCEV - We know that there is no SCEV for the specified value.
1138 /// Analyze the expression.
1139 SCEVHandle createSCEV(Value *V);
Chris Lattner53e677a2004-04-02 20:23:17 +00001140
1141 /// createNodeForPHI - Provide the special handling we need to analyze PHI
1142 /// SCEVs.
1143 SCEVHandle createNodeForPHI(PHINode *PN);
Chris Lattner4dc534c2005-02-13 04:37:18 +00001144
1145 /// ReplaceSymbolicValueWithConcrete - This looks up the computed SCEV value
1146 /// for the specified instruction and replaces any references to the
1147 /// symbolic value SymName with the specified value. This is used during
1148 /// PHI resolution.
1149 void ReplaceSymbolicValueWithConcrete(Instruction *I,
1150 const SCEVHandle &SymName,
1151 const SCEVHandle &NewVal);
Chris Lattner53e677a2004-04-02 20:23:17 +00001152
1153 /// ComputeIterationCount - Compute the number of times the specified loop
1154 /// will iterate.
1155 SCEVHandle ComputeIterationCount(const Loop *L);
1156
Chris Lattner673e02b2004-10-12 01:49:27 +00001157 /// ComputeLoadConstantCompareIterationCount - Given an exit condition of
1158 /// 'setcc load X, cst', try to se if we can compute the trip count.
1159 SCEVHandle ComputeLoadConstantCompareIterationCount(LoadInst *LI,
1160 Constant *RHS,
1161 const Loop *L,
1162 unsigned SetCCOpcode);
1163
Chris Lattner7980fb92004-04-17 18:36:24 +00001164 /// ComputeIterationCountExhaustively - If the trip is known to execute a
1165 /// constant number of times (the condition evolves only from constants),
1166 /// try to evaluate a few iterations of the loop until we get the exit
1167 /// condition gets a value of ExitWhen (true or false). If we cannot
1168 /// evaluate the trip count of the loop, return UnknownValue.
1169 SCEVHandle ComputeIterationCountExhaustively(const Loop *L, Value *Cond,
1170 bool ExitWhen);
1171
Chris Lattner53e677a2004-04-02 20:23:17 +00001172 /// HowFarToZero - Return the number of times a backedge comparing the
1173 /// specified value to zero will execute. If not computable, return
Chris Lattnerdb25de42005-08-15 23:33:51 +00001174 /// UnknownValue.
Chris Lattner53e677a2004-04-02 20:23:17 +00001175 SCEVHandle HowFarToZero(SCEV *V, const Loop *L);
1176
1177 /// HowFarToNonZero - Return the number of times a backedge checking the
1178 /// specified value for nonzero will execute. If not computable, return
Chris Lattnerdb25de42005-08-15 23:33:51 +00001179 /// UnknownValue.
Chris Lattner53e677a2004-04-02 20:23:17 +00001180 SCEVHandle HowFarToNonZero(SCEV *V, const Loop *L);
Chris Lattner3221ad02004-04-17 22:58:41 +00001181
Chris Lattnerdb25de42005-08-15 23:33:51 +00001182 /// HowManyLessThans - Return the number of times a backedge containing the
1183 /// specified less-than comparison will execute. If not computable, return
1184 /// UnknownValue.
1185 SCEVHandle HowManyLessThans(SCEV *LHS, SCEV *RHS, const Loop *L);
1186
Chris Lattner3221ad02004-04-17 22:58:41 +00001187 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
1188 /// in the header of its containing loop, we know the loop executes a
1189 /// constant number of times, and the PHI node is just a recurrence
1190 /// involving constants, fold it.
1191 Constant *getConstantEvolutionLoopExitValue(PHINode *PN, uint64_t Its,
1192 const Loop *L);
Chris Lattner53e677a2004-04-02 20:23:17 +00001193 };
1194}
1195
1196//===----------------------------------------------------------------------===//
1197// Basic SCEV Analysis and PHI Idiom Recognition Code
1198//
1199
1200/// deleteInstructionFromRecords - This method should be called by the
1201/// client before it removes an instruction from the program, to make sure
1202/// that no dangling references are left around.
1203void ScalarEvolutionsImpl::deleteInstructionFromRecords(Instruction *I) {
1204 Scalars.erase(I);
Chris Lattner3221ad02004-04-17 22:58:41 +00001205 if (PHINode *PN = dyn_cast<PHINode>(I))
1206 ConstantEvolutionLoopExitValue.erase(PN);
Chris Lattner53e677a2004-04-02 20:23:17 +00001207}
1208
1209
1210/// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
1211/// expression and create a new one.
1212SCEVHandle ScalarEvolutionsImpl::getSCEV(Value *V) {
1213 assert(V->getType() != Type::VoidTy && "Can't analyze void expressions!");
1214
1215 std::map<Value*, SCEVHandle>::iterator I = Scalars.find(V);
1216 if (I != Scalars.end()) return I->second;
1217 SCEVHandle S = createSCEV(V);
1218 Scalars.insert(std::make_pair(V, S));
1219 return S;
1220}
1221
Chris Lattner4dc534c2005-02-13 04:37:18 +00001222/// ReplaceSymbolicValueWithConcrete - This looks up the computed SCEV value for
1223/// the specified instruction and replaces any references to the symbolic value
1224/// SymName with the specified value. This is used during PHI resolution.
1225void ScalarEvolutionsImpl::
1226ReplaceSymbolicValueWithConcrete(Instruction *I, const SCEVHandle &SymName,
1227 const SCEVHandle &NewVal) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001228 std::map<Value*, SCEVHandle>::iterator SI = Scalars.find(I);
Chris Lattner4dc534c2005-02-13 04:37:18 +00001229 if (SI == Scalars.end()) return;
Chris Lattner53e677a2004-04-02 20:23:17 +00001230
Chris Lattner4dc534c2005-02-13 04:37:18 +00001231 SCEVHandle NV =
1232 SI->second->replaceSymbolicValuesWithConcrete(SymName, NewVal);
1233 if (NV == SI->second) return; // No change.
1234
1235 SI->second = NV; // Update the scalars map!
1236
1237 // Any instruction values that use this instruction might also need to be
1238 // updated!
1239 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1240 UI != E; ++UI)
1241 ReplaceSymbolicValueWithConcrete(cast<Instruction>(*UI), SymName, NewVal);
1242}
Chris Lattner53e677a2004-04-02 20:23:17 +00001243
1244/// createNodeForPHI - PHI nodes have two cases. Either the PHI node exists in
1245/// a loop header, making it a potential recurrence, or it doesn't.
1246///
1247SCEVHandle ScalarEvolutionsImpl::createNodeForPHI(PHINode *PN) {
1248 if (PN->getNumIncomingValues() == 2) // The loops have been canonicalized.
1249 if (const Loop *L = LI.getLoopFor(PN->getParent()))
1250 if (L->getHeader() == PN->getParent()) {
1251 // If it lives in the loop header, it has two incoming values, one
1252 // from outside the loop, and one from inside.
1253 unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0));
1254 unsigned BackEdge = IncomingEdge^1;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001255
Chris Lattner53e677a2004-04-02 20:23:17 +00001256 // While we are analyzing this PHI node, handle its value symbolically.
1257 SCEVHandle SymbolicName = SCEVUnknown::get(PN);
1258 assert(Scalars.find(PN) == Scalars.end() &&
1259 "PHI node already processed?");
1260 Scalars.insert(std::make_pair(PN, SymbolicName));
1261
1262 // Using this symbolic name for the PHI, analyze the value coming around
1263 // the back-edge.
1264 SCEVHandle BEValue = getSCEV(PN->getIncomingValue(BackEdge));
1265
1266 // NOTE: If BEValue is loop invariant, we know that the PHI node just
1267 // has a special value for the first iteration of the loop.
1268
1269 // If the value coming around the backedge is an add with the symbolic
1270 // value we just inserted, then we found a simple induction variable!
1271 if (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
1272 // If there is a single occurrence of the symbolic value, replace it
1273 // with a recurrence.
1274 unsigned FoundIndex = Add->getNumOperands();
1275 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
1276 if (Add->getOperand(i) == SymbolicName)
1277 if (FoundIndex == e) {
1278 FoundIndex = i;
1279 break;
1280 }
1281
1282 if (FoundIndex != Add->getNumOperands()) {
1283 // Create an add with everything but the specified operand.
1284 std::vector<SCEVHandle> Ops;
1285 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
1286 if (i != FoundIndex)
1287 Ops.push_back(Add->getOperand(i));
1288 SCEVHandle Accum = SCEVAddExpr::get(Ops);
1289
1290 // This is not a valid addrec if the step amount is varying each
1291 // loop iteration, but is not itself an addrec in this loop.
1292 if (Accum->isLoopInvariant(L) ||
1293 (isa<SCEVAddRecExpr>(Accum) &&
1294 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
1295 SCEVHandle StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
1296 SCEVHandle PHISCEV = SCEVAddRecExpr::get(StartVal, Accum, L);
1297
1298 // Okay, for the entire analysis of this edge we assumed the PHI
1299 // to be symbolic. We now need to go back and update all of the
1300 // entries for the scalars that use the PHI (except for the PHI
1301 // itself) to use the new analyzed value instead of the "symbolic"
1302 // value.
Chris Lattner4dc534c2005-02-13 04:37:18 +00001303 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
Chris Lattner53e677a2004-04-02 20:23:17 +00001304 return PHISCEV;
1305 }
1306 }
Chris Lattner97156e72006-04-26 18:34:07 +00001307 } else if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(BEValue)) {
1308 // Otherwise, this could be a loop like this:
1309 // i = 0; for (j = 1; ..; ++j) { .... i = j; }
1310 // In this case, j = {1,+,1} and BEValue is j.
1311 // Because the other in-value of i (0) fits the evolution of BEValue
1312 // i really is an addrec evolution.
1313 if (AddRec->getLoop() == L && AddRec->isAffine()) {
1314 SCEVHandle StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
1315
1316 // If StartVal = j.start - j.stride, we can use StartVal as the
1317 // initial step of the addrec evolution.
1318 if (StartVal == SCEV::getMinusSCEV(AddRec->getOperand(0),
1319 AddRec->getOperand(1))) {
1320 SCEVHandle PHISCEV =
1321 SCEVAddRecExpr::get(StartVal, AddRec->getOperand(1), L);
1322
1323 // Okay, for the entire analysis of this edge we assumed the PHI
1324 // to be symbolic. We now need to go back and update all of the
1325 // entries for the scalars that use the PHI (except for the PHI
1326 // itself) to use the new analyzed value instead of the "symbolic"
1327 // value.
1328 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
1329 return PHISCEV;
1330 }
1331 }
Chris Lattner53e677a2004-04-02 20:23:17 +00001332 }
1333
1334 return SymbolicName;
1335 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001336
Chris Lattner53e677a2004-04-02 20:23:17 +00001337 // If it's not a loop phi, we can't handle it yet.
1338 return SCEVUnknown::get(PN);
1339}
1340
Chris Lattner53e677a2004-04-02 20:23:17 +00001341
1342/// createSCEV - We know that there is no SCEV for the specified value.
1343/// Analyze the expression.
1344///
1345SCEVHandle ScalarEvolutionsImpl::createSCEV(Value *V) {
1346 if (Instruction *I = dyn_cast<Instruction>(V)) {
1347 switch (I->getOpcode()) {
1348 case Instruction::Add:
1349 return SCEVAddExpr::get(getSCEV(I->getOperand(0)),
1350 getSCEV(I->getOperand(1)));
1351 case Instruction::Mul:
1352 return SCEVMulExpr::get(getSCEV(I->getOperand(0)),
1353 getSCEV(I->getOperand(1)));
Reid Spencer1628cec2006-10-26 06:15:43 +00001354 case Instruction::SDiv:
1355 return SCEVSDivExpr::get(getSCEV(I->getOperand(0)),
1356 getSCEV(I->getOperand(1)));
Chris Lattner53e677a2004-04-02 20:23:17 +00001357 break;
1358
1359 case Instruction::Sub:
Chris Lattnerbac5b462005-03-09 05:34:41 +00001360 return SCEV::getMinusSCEV(getSCEV(I->getOperand(0)),
1361 getSCEV(I->getOperand(1)));
Chris Lattner53e677a2004-04-02 20:23:17 +00001362
1363 case Instruction::Shl:
1364 // Turn shift left of a constant amount into a multiply.
1365 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1366 Constant *X = ConstantInt::get(V->getType(), 1);
1367 X = ConstantExpr::getShl(X, SA);
1368 return SCEVMulExpr::get(getSCEV(I->getOperand(0)), getSCEV(X));
1369 }
1370 break;
1371
Reid Spencer3da59db2006-11-27 01:05:10 +00001372 case Instruction::Trunc:
1373 if (I->getType()->isInteger() && I->getOperand(0)->getType()->isInteger())
1374 return SCEVTruncateExpr::get(getSCEV(I->getOperand(0)),
1375 I->getType()->getUnsignedVersion());
1376 break;
1377
1378 case Instruction::ZExt:
1379 if (I->getType()->isInteger() && I->getOperand(0)->getType()->isInteger())
1380 return SCEVZeroExtendExpr::get(getSCEV(I->getOperand(0)),
1381 I->getType()->getUnsignedVersion());
1382 break;
1383
1384 case Instruction::BitCast:
1385 // BitCasts are no-op casts so we just eliminate the cast.
1386 return getSCEV(I->getOperand(0));
Chris Lattner53e677a2004-04-02 20:23:17 +00001387
1388 case Instruction::PHI:
1389 return createNodeForPHI(cast<PHINode>(I));
1390
1391 default: // We cannot analyze this expression.
1392 break;
1393 }
1394 }
1395
1396 return SCEVUnknown::get(V);
1397}
1398
1399
1400
1401//===----------------------------------------------------------------------===//
1402// Iteration Count Computation Code
1403//
1404
1405/// getIterationCount - If the specified loop has a predictable iteration
1406/// count, return it. Note that it is not valid to call this method on a
1407/// loop without a loop-invariant iteration count.
1408SCEVHandle ScalarEvolutionsImpl::getIterationCount(const Loop *L) {
1409 std::map<const Loop*, SCEVHandle>::iterator I = IterationCounts.find(L);
1410 if (I == IterationCounts.end()) {
1411 SCEVHandle ItCount = ComputeIterationCount(L);
1412 I = IterationCounts.insert(std::make_pair(L, ItCount)).first;
1413 if (ItCount != UnknownValue) {
1414 assert(ItCount->isLoopInvariant(L) &&
1415 "Computed trip count isn't loop invariant for loop!");
1416 ++NumTripCountsComputed;
1417 } else if (isa<PHINode>(L->getHeader()->begin())) {
1418 // Only count loops that have phi nodes as not being computable.
1419 ++NumTripCountsNotComputed;
1420 }
1421 }
1422 return I->second;
1423}
1424
1425/// ComputeIterationCount - Compute the number of times the specified loop
1426/// will iterate.
1427SCEVHandle ScalarEvolutionsImpl::ComputeIterationCount(const Loop *L) {
1428 // If the loop has a non-one exit block count, we can't analyze it.
Chris Lattnerf1ab4b42004-04-18 22:14:10 +00001429 std::vector<BasicBlock*> ExitBlocks;
1430 L->getExitBlocks(ExitBlocks);
1431 if (ExitBlocks.size() != 1) return UnknownValue;
Chris Lattner53e677a2004-04-02 20:23:17 +00001432
1433 // Okay, there is one exit block. Try to find the condition that causes the
1434 // loop to be exited.
Chris Lattnerf1ab4b42004-04-18 22:14:10 +00001435 BasicBlock *ExitBlock = ExitBlocks[0];
Chris Lattner53e677a2004-04-02 20:23:17 +00001436
1437 BasicBlock *ExitingBlock = 0;
1438 for (pred_iterator PI = pred_begin(ExitBlock), E = pred_end(ExitBlock);
1439 PI != E; ++PI)
1440 if (L->contains(*PI)) {
1441 if (ExitingBlock == 0)
1442 ExitingBlock = *PI;
1443 else
1444 return UnknownValue; // More than one block exiting!
1445 }
1446 assert(ExitingBlock && "No exits from loop, something is broken!");
1447
1448 // Okay, we've computed the exiting block. See what condition causes us to
1449 // exit.
1450 //
1451 // FIXME: we should be able to handle switch instructions (with a single exit)
1452 // FIXME: We should handle cast of int to bool as well
1453 BranchInst *ExitBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
1454 if (ExitBr == 0) return UnknownValue;
1455 assert(ExitBr->isConditional() && "If unconditional, it can't be in loop!");
1456 SetCondInst *ExitCond = dyn_cast<SetCondInst>(ExitBr->getCondition());
Chris Lattner7980fb92004-04-17 18:36:24 +00001457 if (ExitCond == 0) // Not a setcc
1458 return ComputeIterationCountExhaustively(L, ExitBr->getCondition(),
1459 ExitBr->getSuccessor(0) == ExitBlock);
Chris Lattner53e677a2004-04-02 20:23:17 +00001460
Chris Lattner673e02b2004-10-12 01:49:27 +00001461 // If the condition was exit on true, convert the condition to exit on false.
1462 Instruction::BinaryOps Cond;
1463 if (ExitBr->getSuccessor(1) == ExitBlock)
1464 Cond = ExitCond->getOpcode();
1465 else
1466 Cond = ExitCond->getInverseCondition();
1467
1468 // Handle common loops like: for (X = "string"; *X; ++X)
1469 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
1470 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
1471 SCEVHandle ItCnt =
1472 ComputeLoadConstantCompareIterationCount(LI, RHS, L, Cond);
1473 if (!isa<SCEVCouldNotCompute>(ItCnt)) return ItCnt;
1474 }
1475
Chris Lattner53e677a2004-04-02 20:23:17 +00001476 SCEVHandle LHS = getSCEV(ExitCond->getOperand(0));
1477 SCEVHandle RHS = getSCEV(ExitCond->getOperand(1));
1478
1479 // Try to evaluate any dependencies out of the loop.
1480 SCEVHandle Tmp = getSCEVAtScope(LHS, L);
1481 if (!isa<SCEVCouldNotCompute>(Tmp)) LHS = Tmp;
1482 Tmp = getSCEVAtScope(RHS, L);
1483 if (!isa<SCEVCouldNotCompute>(Tmp)) RHS = Tmp;
1484
Chris Lattner53e677a2004-04-02 20:23:17 +00001485 // At this point, we would like to compute how many iterations of the loop the
1486 // predicate will return true for these inputs.
1487 if (isa<SCEVConstant>(LHS) && !isa<SCEVConstant>(RHS)) {
1488 // If there is a constant, force it into the RHS.
1489 std::swap(LHS, RHS);
1490 Cond = SetCondInst::getSwappedCondition(Cond);
1491 }
1492
1493 // FIXME: think about handling pointer comparisons! i.e.:
1494 // while (P != P+100) ++P;
1495
1496 // If we have a comparison of a chrec against a constant, try to use value
1497 // ranges to answer this query.
1498 if (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
1499 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
1500 if (AddRec->getLoop() == L) {
1501 // Form the comparison range using the constant of the correct type so
1502 // that the ConstantRange class knows to do a signed or unsigned
1503 // comparison.
1504 ConstantInt *CompVal = RHSC->getValue();
1505 const Type *RealTy = ExitCond->getOperand(0)->getType();
1506 CompVal = dyn_cast<ConstantInt>(ConstantExpr::getCast(CompVal, RealTy));
1507 if (CompVal) {
1508 // Form the constant range.
1509 ConstantRange CompRange(Cond, CompVal);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001510
Chris Lattner53e677a2004-04-02 20:23:17 +00001511 // Now that we have it, if it's signed, convert it to an unsigned
1512 // range.
1513 if (CompRange.getLower()->getType()->isSigned()) {
1514 const Type *NewTy = RHSC->getValue()->getType();
1515 Constant *NewL = ConstantExpr::getCast(CompRange.getLower(), NewTy);
1516 Constant *NewU = ConstantExpr::getCast(CompRange.getUpper(), NewTy);
1517 CompRange = ConstantRange(NewL, NewU);
1518 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001519
Chris Lattner53e677a2004-04-02 20:23:17 +00001520 SCEVHandle Ret = AddRec->getNumIterationsInRange(CompRange);
1521 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
1522 }
1523 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001524
Chris Lattner53e677a2004-04-02 20:23:17 +00001525 switch (Cond) {
1526 case Instruction::SetNE: // while (X != Y)
1527 // Convert to: while (X-Y != 0)
Chris Lattner7980fb92004-04-17 18:36:24 +00001528 if (LHS->getType()->isInteger()) {
Chris Lattnerbac5b462005-03-09 05:34:41 +00001529 SCEVHandle TC = HowFarToZero(SCEV::getMinusSCEV(LHS, RHS), L);
Chris Lattner7980fb92004-04-17 18:36:24 +00001530 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
1531 }
Chris Lattner53e677a2004-04-02 20:23:17 +00001532 break;
1533 case Instruction::SetEQ:
1534 // Convert to: while (X-Y == 0) // while (X == Y)
Chris Lattner7980fb92004-04-17 18:36:24 +00001535 if (LHS->getType()->isInteger()) {
Chris Lattnerbac5b462005-03-09 05:34:41 +00001536 SCEVHandle TC = HowFarToNonZero(SCEV::getMinusSCEV(LHS, RHS), L);
Chris Lattner7980fb92004-04-17 18:36:24 +00001537 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
1538 }
Chris Lattner53e677a2004-04-02 20:23:17 +00001539 break;
Chris Lattnerdb25de42005-08-15 23:33:51 +00001540 case Instruction::SetLT:
1541 if (LHS->getType()->isInteger() &&
1542 ExitCond->getOperand(0)->getType()->isSigned()) {
1543 SCEVHandle TC = HowManyLessThans(LHS, RHS, L);
1544 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
1545 }
1546 break;
1547 case Instruction::SetGT:
1548 if (LHS->getType()->isInteger() &&
1549 ExitCond->getOperand(0)->getType()->isSigned()) {
1550 SCEVHandle TC = HowManyLessThans(RHS, LHS, L);
1551 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
1552 }
1553 break;
Chris Lattner53e677a2004-04-02 20:23:17 +00001554 default:
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00001555#if 0
Chris Lattner53e677a2004-04-02 20:23:17 +00001556 std::cerr << "ComputeIterationCount ";
1557 if (ExitCond->getOperand(0)->getType()->isUnsigned())
1558 std::cerr << "[unsigned] ";
1559 std::cerr << *LHS << " "
1560 << Instruction::getOpcodeName(Cond) << " " << *RHS << "\n";
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00001561#endif
Chris Lattnere34c0b42004-04-03 00:43:03 +00001562 break;
Chris Lattner53e677a2004-04-02 20:23:17 +00001563 }
Chris Lattner7980fb92004-04-17 18:36:24 +00001564
1565 return ComputeIterationCountExhaustively(L, ExitCond,
1566 ExitBr->getSuccessor(0) == ExitBlock);
1567}
1568
Chris Lattner673e02b2004-10-12 01:49:27 +00001569static ConstantInt *
1570EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, Constant *C) {
1571 SCEVHandle InVal = SCEVConstant::get(cast<ConstantInt>(C));
1572 SCEVHandle Val = AddRec->evaluateAtIteration(InVal);
1573 assert(isa<SCEVConstant>(Val) &&
1574 "Evaluation of SCEV at constant didn't fold correctly?");
1575 return cast<SCEVConstant>(Val)->getValue();
1576}
1577
1578/// GetAddressedElementFromGlobal - Given a global variable with an initializer
1579/// and a GEP expression (missing the pointer index) indexing into it, return
1580/// the addressed element of the initializer or null if the index expression is
1581/// invalid.
1582static Constant *
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001583GetAddressedElementFromGlobal(GlobalVariable *GV,
Chris Lattner673e02b2004-10-12 01:49:27 +00001584 const std::vector<ConstantInt*> &Indices) {
1585 Constant *Init = GV->getInitializer();
1586 for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
Reid Spencerb83eb642006-10-20 07:07:24 +00001587 uint64_t Idx = Indices[i]->getZExtValue();
Chris Lattner673e02b2004-10-12 01:49:27 +00001588 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
1589 assert(Idx < CS->getNumOperands() && "Bad struct index!");
1590 Init = cast<Constant>(CS->getOperand(Idx));
1591 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
1592 if (Idx >= CA->getNumOperands()) return 0; // Bogus program
1593 Init = cast<Constant>(CA->getOperand(Idx));
1594 } else if (isa<ConstantAggregateZero>(Init)) {
1595 if (const StructType *STy = dyn_cast<StructType>(Init->getType())) {
1596 assert(Idx < STy->getNumElements() && "Bad struct index!");
1597 Init = Constant::getNullValue(STy->getElementType(Idx));
1598 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Init->getType())) {
1599 if (Idx >= ATy->getNumElements()) return 0; // Bogus program
1600 Init = Constant::getNullValue(ATy->getElementType());
1601 } else {
1602 assert(0 && "Unknown constant aggregate type!");
1603 }
1604 return 0;
1605 } else {
1606 return 0; // Unknown initializer type
1607 }
1608 }
1609 return Init;
1610}
1611
1612/// ComputeLoadConstantCompareIterationCount - Given an exit condition of
1613/// 'setcc load X, cst', try to se if we can compute the trip count.
1614SCEVHandle ScalarEvolutionsImpl::
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001615ComputeLoadConstantCompareIterationCount(LoadInst *LI, Constant *RHS,
Chris Lattner673e02b2004-10-12 01:49:27 +00001616 const Loop *L, unsigned SetCCOpcode) {
1617 if (LI->isVolatile()) return UnknownValue;
1618
1619 // Check to see if the loaded pointer is a getelementptr of a global.
1620 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
1621 if (!GEP) return UnknownValue;
1622
1623 // Make sure that it is really a constant global we are gepping, with an
1624 // initializer, and make sure the first IDX is really 0.
1625 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
1626 if (!GV || !GV->isConstant() || !GV->hasInitializer() ||
1627 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
1628 !cast<Constant>(GEP->getOperand(1))->isNullValue())
1629 return UnknownValue;
1630
1631 // Okay, we allow one non-constant index into the GEP instruction.
1632 Value *VarIdx = 0;
1633 std::vector<ConstantInt*> Indexes;
1634 unsigned VarIdxNum = 0;
1635 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
1636 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
1637 Indexes.push_back(CI);
1638 } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
1639 if (VarIdx) return UnknownValue; // Multiple non-constant idx's.
1640 VarIdx = GEP->getOperand(i);
1641 VarIdxNum = i-2;
1642 Indexes.push_back(0);
1643 }
1644
1645 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
1646 // Check to see if X is a loop variant variable value now.
1647 SCEVHandle Idx = getSCEV(VarIdx);
1648 SCEVHandle Tmp = getSCEVAtScope(Idx, L);
1649 if (!isa<SCEVCouldNotCompute>(Tmp)) Idx = Tmp;
1650
1651 // We can only recognize very limited forms of loop index expressions, in
1652 // particular, only affine AddRec's like {C1,+,C2}.
1653 SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
1654 if (!IdxExpr || !IdxExpr->isAffine() || IdxExpr->isLoopInvariant(L) ||
1655 !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
1656 !isa<SCEVConstant>(IdxExpr->getOperand(1)))
1657 return UnknownValue;
1658
1659 unsigned MaxSteps = MaxBruteForceIterations;
1660 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
Reid Spencerb83eb642006-10-20 07:07:24 +00001661 ConstantInt *ItCst =
1662 ConstantInt::get(IdxExpr->getType()->getUnsignedVersion(), IterationNum);
Chris Lattner673e02b2004-10-12 01:49:27 +00001663 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst);
1664
1665 // Form the GEP offset.
1666 Indexes[VarIdxNum] = Val;
1667
1668 Constant *Result = GetAddressedElementFromGlobal(GV, Indexes);
1669 if (Result == 0) break; // Cannot compute!
1670
1671 // Evaluate the condition for this iteration.
1672 Result = ConstantExpr::get(SetCCOpcode, Result, RHS);
1673 if (!isa<ConstantBool>(Result)) break; // Couldn't decide for sure
Chris Lattner003cbf32006-09-28 23:36:21 +00001674 if (cast<ConstantBool>(Result)->getValue() == false) {
Chris Lattner673e02b2004-10-12 01:49:27 +00001675#if 0
1676 std::cerr << "\n***\n*** Computed loop count " << *ItCst
1677 << "\n*** From global " << *GV << "*** BB: " << *L->getHeader()
1678 << "***\n";
1679#endif
1680 ++NumArrayLenItCounts;
1681 return SCEVConstant::get(ItCst); // Found terminating iteration!
1682 }
1683 }
1684 return UnknownValue;
1685}
1686
1687
Chris Lattner3221ad02004-04-17 22:58:41 +00001688/// CanConstantFold - Return true if we can constant fold an instruction of the
1689/// specified type, assuming that all operands were constants.
1690static bool CanConstantFold(const Instruction *I) {
1691 if (isa<BinaryOperator>(I) || isa<ShiftInst>(I) ||
1692 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I))
1693 return true;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001694
Chris Lattner3221ad02004-04-17 22:58:41 +00001695 if (const CallInst *CI = dyn_cast<CallInst>(I))
1696 if (const Function *F = CI->getCalledFunction())
1697 return canConstantFoldCallTo((Function*)F); // FIXME: elim cast
1698 return false;
Chris Lattner7980fb92004-04-17 18:36:24 +00001699}
1700
Chris Lattner3221ad02004-04-17 22:58:41 +00001701/// ConstantFold - Constant fold an instruction of the specified type with the
1702/// specified constant operands. This function may modify the operands vector.
1703static Constant *ConstantFold(const Instruction *I,
1704 std::vector<Constant*> &Operands) {
Chris Lattner7980fb92004-04-17 18:36:24 +00001705 if (isa<BinaryOperator>(I) || isa<ShiftInst>(I))
1706 return ConstantExpr::get(I->getOpcode(), Operands[0], Operands[1]);
1707
Reid Spencer3da59db2006-11-27 01:05:10 +00001708 if (isa<CastInst>(I))
1709 return ConstantExpr::getCast(I->getOpcode(), Operands[0], I->getType());
1710
Chris Lattner7980fb92004-04-17 18:36:24 +00001711 switch (I->getOpcode()) {
Chris Lattner7980fb92004-04-17 18:36:24 +00001712 case Instruction::Select:
1713 return ConstantExpr::getSelect(Operands[0], Operands[1], Operands[2]);
1714 case Instruction::Call:
Reid Spencere8404342004-07-18 00:18:30 +00001715 if (Function *GV = dyn_cast<Function>(Operands[0])) {
Chris Lattner7980fb92004-04-17 18:36:24 +00001716 Operands.erase(Operands.begin());
Reid Spencere8404342004-07-18 00:18:30 +00001717 return ConstantFoldCall(cast<Function>(GV), Operands);
Chris Lattner7980fb92004-04-17 18:36:24 +00001718 }
Chris Lattner7980fb92004-04-17 18:36:24 +00001719 return 0;
1720 case Instruction::GetElementPtr:
1721 Constant *Base = Operands[0];
1722 Operands.erase(Operands.begin());
1723 return ConstantExpr::getGetElementPtr(Base, Operands);
1724 }
1725 return 0;
1726}
1727
1728
Chris Lattner3221ad02004-04-17 22:58:41 +00001729/// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
1730/// in the loop that V is derived from. We allow arbitrary operations along the
1731/// way, but the operands of an operation must either be constants or a value
1732/// derived from a constant PHI. If this expression does not fit with these
1733/// constraints, return null.
1734static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
1735 // If this is not an instruction, or if this is an instruction outside of the
1736 // loop, it can't be derived from a loop PHI.
1737 Instruction *I = dyn_cast<Instruction>(V);
1738 if (I == 0 || !L->contains(I->getParent())) return 0;
1739
1740 if (PHINode *PN = dyn_cast<PHINode>(I))
1741 if (L->getHeader() == I->getParent())
1742 return PN;
1743 else
1744 // We don't currently keep track of the control flow needed to evaluate
1745 // PHIs, so we cannot handle PHIs inside of loops.
1746 return 0;
1747
1748 // If we won't be able to constant fold this expression even if the operands
1749 // are constants, return early.
1750 if (!CanConstantFold(I)) return 0;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001751
Chris Lattner3221ad02004-04-17 22:58:41 +00001752 // Otherwise, we can evaluate this instruction if all of its operands are
1753 // constant or derived from a PHI node themselves.
1754 PHINode *PHI = 0;
1755 for (unsigned Op = 0, e = I->getNumOperands(); Op != e; ++Op)
1756 if (!(isa<Constant>(I->getOperand(Op)) ||
1757 isa<GlobalValue>(I->getOperand(Op)))) {
1758 PHINode *P = getConstantEvolvingPHI(I->getOperand(Op), L);
1759 if (P == 0) return 0; // Not evolving from PHI
1760 if (PHI == 0)
1761 PHI = P;
1762 else if (PHI != P)
1763 return 0; // Evolving from multiple different PHIs.
1764 }
1765
1766 // This is a expression evolving from a constant PHI!
1767 return PHI;
1768}
1769
1770/// EvaluateExpression - Given an expression that passes the
1771/// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
1772/// in the loop has the value PHIVal. If we can't fold this expression for some
1773/// reason, return null.
1774static Constant *EvaluateExpression(Value *V, Constant *PHIVal) {
1775 if (isa<PHINode>(V)) return PHIVal;
Chris Lattner3221ad02004-04-17 22:58:41 +00001776 if (GlobalValue *GV = dyn_cast<GlobalValue>(V))
Reid Spencere8404342004-07-18 00:18:30 +00001777 return GV;
1778 if (Constant *C = dyn_cast<Constant>(V)) return C;
Chris Lattner3221ad02004-04-17 22:58:41 +00001779 Instruction *I = cast<Instruction>(V);
1780
1781 std::vector<Constant*> Operands;
1782 Operands.resize(I->getNumOperands());
1783
1784 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
1785 Operands[i] = EvaluateExpression(I->getOperand(i), PHIVal);
1786 if (Operands[i] == 0) return 0;
1787 }
1788
1789 return ConstantFold(I, Operands);
1790}
1791
1792/// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
1793/// in the header of its containing loop, we know the loop executes a
1794/// constant number of times, and the PHI node is just a recurrence
1795/// involving constants, fold it.
1796Constant *ScalarEvolutionsImpl::
1797getConstantEvolutionLoopExitValue(PHINode *PN, uint64_t Its, const Loop *L) {
1798 std::map<PHINode*, Constant*>::iterator I =
1799 ConstantEvolutionLoopExitValue.find(PN);
1800 if (I != ConstantEvolutionLoopExitValue.end())
1801 return I->second;
1802
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001803 if (Its > MaxBruteForceIterations)
Chris Lattner3221ad02004-04-17 22:58:41 +00001804 return ConstantEvolutionLoopExitValue[PN] = 0; // Not going to evaluate it.
1805
1806 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
1807
1808 // Since the loop is canonicalized, the PHI node must have two entries. One
1809 // entry must be a constant (coming in from outside of the loop), and the
1810 // second must be derived from the same PHI.
1811 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
1812 Constant *StartCST =
1813 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
1814 if (StartCST == 0)
1815 return RetVal = 0; // Must be a constant.
1816
1817 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
1818 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
1819 if (PN2 != PN)
1820 return RetVal = 0; // Not derived from same PHI.
1821
1822 // Execute the loop symbolically to determine the exit value.
1823 unsigned IterationNum = 0;
1824 unsigned NumIterations = Its;
1825 if (NumIterations != Its)
1826 return RetVal = 0; // More than 2^32 iterations??
1827
1828 for (Constant *PHIVal = StartCST; ; ++IterationNum) {
1829 if (IterationNum == NumIterations)
1830 return RetVal = PHIVal; // Got exit value!
1831
1832 // Compute the value of the PHI node for the next iteration.
1833 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
1834 if (NextPHI == PHIVal)
1835 return RetVal = NextPHI; // Stopped evolving!
1836 if (NextPHI == 0)
1837 return 0; // Couldn't evaluate!
1838 PHIVal = NextPHI;
1839 }
1840}
1841
Chris Lattner7980fb92004-04-17 18:36:24 +00001842/// ComputeIterationCountExhaustively - If the trip is known to execute a
1843/// constant number of times (the condition evolves only from constants),
1844/// try to evaluate a few iterations of the loop until we get the exit
1845/// condition gets a value of ExitWhen (true or false). If we cannot
1846/// evaluate the trip count of the loop, return UnknownValue.
1847SCEVHandle ScalarEvolutionsImpl::
1848ComputeIterationCountExhaustively(const Loop *L, Value *Cond, bool ExitWhen) {
1849 PHINode *PN = getConstantEvolvingPHI(Cond, L);
1850 if (PN == 0) return UnknownValue;
1851
1852 // Since the loop is canonicalized, the PHI node must have two entries. One
1853 // entry must be a constant (coming in from outside of the loop), and the
1854 // second must be derived from the same PHI.
1855 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
1856 Constant *StartCST =
1857 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
1858 if (StartCST == 0) return UnknownValue; // Must be a constant.
1859
1860 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
1861 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
1862 if (PN2 != PN) return UnknownValue; // Not derived from same PHI.
1863
1864 // Okay, we find a PHI node that defines the trip count of this loop. Execute
1865 // the loop symbolically to determine when the condition gets a value of
1866 // "ExitWhen".
1867 unsigned IterationNum = 0;
1868 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis.
1869 for (Constant *PHIVal = StartCST;
1870 IterationNum != MaxIterations; ++IterationNum) {
1871 ConstantBool *CondVal =
1872 dyn_cast_or_null<ConstantBool>(EvaluateExpression(Cond, PHIVal));
1873 if (!CondVal) return UnknownValue; // Couldn't symbolically evaluate.
Chris Lattner3221ad02004-04-17 22:58:41 +00001874
Chris Lattner7980fb92004-04-17 18:36:24 +00001875 if (CondVal->getValue() == ExitWhen) {
Chris Lattner3221ad02004-04-17 22:58:41 +00001876 ConstantEvolutionLoopExitValue[PN] = PHIVal;
Chris Lattner7980fb92004-04-17 18:36:24 +00001877 ++NumBruteForceTripCountsComputed;
Reid Spencerb83eb642006-10-20 07:07:24 +00001878 return SCEVConstant::get(ConstantInt::get(Type::UIntTy, IterationNum));
Chris Lattner7980fb92004-04-17 18:36:24 +00001879 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001880
Chris Lattner3221ad02004-04-17 22:58:41 +00001881 // Compute the value of the PHI node for the next iteration.
1882 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
1883 if (NextPHI == 0 || NextPHI == PHIVal)
Chris Lattner7980fb92004-04-17 18:36:24 +00001884 return UnknownValue; // Couldn't evaluate or not making progress...
Chris Lattner3221ad02004-04-17 22:58:41 +00001885 PHIVal = NextPHI;
Chris Lattner7980fb92004-04-17 18:36:24 +00001886 }
1887
1888 // Too many iterations were needed to evaluate.
Chris Lattner53e677a2004-04-02 20:23:17 +00001889 return UnknownValue;
1890}
1891
1892/// getSCEVAtScope - Compute the value of the specified expression within the
1893/// indicated loop (which may be null to indicate in no loop). If the
1894/// expression cannot be evaluated, return UnknownValue.
1895SCEVHandle ScalarEvolutionsImpl::getSCEVAtScope(SCEV *V, const Loop *L) {
1896 // FIXME: this should be turned into a virtual method on SCEV!
1897
Chris Lattner3221ad02004-04-17 22:58:41 +00001898 if (isa<SCEVConstant>(V)) return V;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001899
Chris Lattner3221ad02004-04-17 22:58:41 +00001900 // If this instruction is evolves from a constant-evolving PHI, compute the
1901 // exit value from the loop without using SCEVs.
1902 if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
1903 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
1904 const Loop *LI = this->LI[I->getParent()];
1905 if (LI && LI->getParentLoop() == L) // Looking for loop exit value.
1906 if (PHINode *PN = dyn_cast<PHINode>(I))
1907 if (PN->getParent() == LI->getHeader()) {
1908 // Okay, there is no closed form solution for the PHI node. Check
1909 // to see if the loop that contains it has a known iteration count.
1910 // If so, we may be able to force computation of the exit value.
1911 SCEVHandle IterationCount = getIterationCount(LI);
1912 if (SCEVConstant *ICC = dyn_cast<SCEVConstant>(IterationCount)) {
1913 // Okay, we know how many times the containing loop executes. If
1914 // this is a constant evolving PHI node, get the final value at
1915 // the specified iteration number.
1916 Constant *RV = getConstantEvolutionLoopExitValue(PN,
Reid Spencerb83eb642006-10-20 07:07:24 +00001917 ICC->getValue()->getZExtValue(),
Chris Lattner3221ad02004-04-17 22:58:41 +00001918 LI);
1919 if (RV) return SCEVUnknown::get(RV);
1920 }
1921 }
1922
1923 // Okay, this is a some expression that we cannot symbolically evaluate
1924 // into a SCEV. Check to see if it's possible to symbolically evaluate
1925 // the arguments into constants, and if see, try to constant propagate the
1926 // result. This is particularly useful for computing loop exit values.
1927 if (CanConstantFold(I)) {
1928 std::vector<Constant*> Operands;
1929 Operands.reserve(I->getNumOperands());
1930 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
1931 Value *Op = I->getOperand(i);
1932 if (Constant *C = dyn_cast<Constant>(Op)) {
1933 Operands.push_back(C);
Chris Lattner3221ad02004-04-17 22:58:41 +00001934 } else {
1935 SCEVHandle OpV = getSCEVAtScope(getSCEV(Op), L);
1936 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(OpV))
1937 Operands.push_back(ConstantExpr::getCast(SC->getValue(),
1938 Op->getType()));
1939 else if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(OpV)) {
1940 if (Constant *C = dyn_cast<Constant>(SU->getValue()))
1941 Operands.push_back(ConstantExpr::getCast(C, Op->getType()));
1942 else
1943 return V;
1944 } else {
1945 return V;
1946 }
1947 }
1948 }
1949 return SCEVUnknown::get(ConstantFold(I, Operands));
1950 }
1951 }
1952
1953 // This is some other type of SCEVUnknown, just return it.
1954 return V;
1955 }
1956
Chris Lattner53e677a2004-04-02 20:23:17 +00001957 if (SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
1958 // Avoid performing the look-up in the common case where the specified
1959 // expression has no loop-variant portions.
1960 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
1961 SCEVHandle OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
1962 if (OpAtScope != Comm->getOperand(i)) {
1963 if (OpAtScope == UnknownValue) return UnknownValue;
1964 // Okay, at least one of these operands is loop variant but might be
1965 // foldable. Build a new instance of the folded commutative expression.
Chris Lattner3221ad02004-04-17 22:58:41 +00001966 std::vector<SCEVHandle> NewOps(Comm->op_begin(), Comm->op_begin()+i);
Chris Lattner53e677a2004-04-02 20:23:17 +00001967 NewOps.push_back(OpAtScope);
1968
1969 for (++i; i != e; ++i) {
1970 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
1971 if (OpAtScope == UnknownValue) return UnknownValue;
1972 NewOps.push_back(OpAtScope);
1973 }
1974 if (isa<SCEVAddExpr>(Comm))
1975 return SCEVAddExpr::get(NewOps);
1976 assert(isa<SCEVMulExpr>(Comm) && "Only know about add and mul!");
1977 return SCEVMulExpr::get(NewOps);
1978 }
1979 }
1980 // If we got here, all operands are loop invariant.
1981 return Comm;
1982 }
1983
Chris Lattner60a05cc2006-04-01 04:48:52 +00001984 if (SCEVSDivExpr *Div = dyn_cast<SCEVSDivExpr>(V)) {
1985 SCEVHandle LHS = getSCEVAtScope(Div->getLHS(), L);
Chris Lattner53e677a2004-04-02 20:23:17 +00001986 if (LHS == UnknownValue) return LHS;
Chris Lattner60a05cc2006-04-01 04:48:52 +00001987 SCEVHandle RHS = getSCEVAtScope(Div->getRHS(), L);
Chris Lattner53e677a2004-04-02 20:23:17 +00001988 if (RHS == UnknownValue) return RHS;
Chris Lattner60a05cc2006-04-01 04:48:52 +00001989 if (LHS == Div->getLHS() && RHS == Div->getRHS())
1990 return Div; // must be loop invariant
1991 return SCEVSDivExpr::get(LHS, RHS);
Chris Lattner53e677a2004-04-02 20:23:17 +00001992 }
1993
1994 // If this is a loop recurrence for a loop that does not contain L, then we
1995 // are dealing with the final value computed by the loop.
1996 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
1997 if (!L || !AddRec->getLoop()->contains(L->getHeader())) {
1998 // To evaluate this recurrence, we need to know how many times the AddRec
1999 // loop iterates. Compute this now.
2000 SCEVHandle IterationCount = getIterationCount(AddRec->getLoop());
2001 if (IterationCount == UnknownValue) return UnknownValue;
2002 IterationCount = getTruncateOrZeroExtend(IterationCount,
2003 AddRec->getType());
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002004
Chris Lattner53e677a2004-04-02 20:23:17 +00002005 // If the value is affine, simplify the expression evaluation to just
2006 // Start + Step*IterationCount.
2007 if (AddRec->isAffine())
2008 return SCEVAddExpr::get(AddRec->getStart(),
2009 SCEVMulExpr::get(IterationCount,
2010 AddRec->getOperand(1)));
2011
2012 // Otherwise, evaluate it the hard way.
2013 return AddRec->evaluateAtIteration(IterationCount);
2014 }
2015 return UnknownValue;
2016 }
2017
2018 //assert(0 && "Unknown SCEV type!");
2019 return UnknownValue;
2020}
2021
2022
2023/// SolveQuadraticEquation - Find the roots of the quadratic equation for the
2024/// given quadratic chrec {L,+,M,+,N}. This returns either the two roots (which
2025/// might be the same) or two SCEVCouldNotCompute objects.
2026///
2027static std::pair<SCEVHandle,SCEVHandle>
2028SolveQuadraticEquation(const SCEVAddRecExpr *AddRec) {
2029 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
2030 SCEVConstant *L = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
2031 SCEVConstant *M = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
2032 SCEVConstant *N = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002033
Chris Lattner53e677a2004-04-02 20:23:17 +00002034 // We currently can only solve this if the coefficients are constants.
2035 if (!L || !M || !N) {
2036 SCEV *CNC = new SCEVCouldNotCompute();
2037 return std::make_pair(CNC, CNC);
2038 }
2039
Reid Spencer1628cec2006-10-26 06:15:43 +00002040 Constant *C = L->getValue();
2041 Constant *Two = ConstantInt::get(C->getType(), 2);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002042
Chris Lattner53e677a2004-04-02 20:23:17 +00002043 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
Chris Lattner53e677a2004-04-02 20:23:17 +00002044 // The B coefficient is M-N/2
2045 Constant *B = ConstantExpr::getSub(M->getValue(),
Reid Spencer1628cec2006-10-26 06:15:43 +00002046 ConstantExpr::getSDiv(N->getValue(),
Chris Lattner53e677a2004-04-02 20:23:17 +00002047 Two));
2048 // The A coefficient is N/2
Reid Spencer1628cec2006-10-26 06:15:43 +00002049 Constant *A = ConstantExpr::getSDiv(N->getValue(), Two);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002050
Chris Lattner53e677a2004-04-02 20:23:17 +00002051 // Compute the B^2-4ac term.
2052 Constant *SqrtTerm =
2053 ConstantExpr::getMul(ConstantInt::get(C->getType(), 4),
2054 ConstantExpr::getMul(A, C));
2055 SqrtTerm = ConstantExpr::getSub(ConstantExpr::getMul(B, B), SqrtTerm);
2056
2057 // Compute floor(sqrt(B^2-4ac))
Reid Spencerb83eb642006-10-20 07:07:24 +00002058 ConstantInt *SqrtVal =
2059 cast<ConstantInt>(ConstantExpr::getCast(SqrtTerm,
Chris Lattner53e677a2004-04-02 20:23:17 +00002060 SqrtTerm->getType()->getUnsignedVersion()));
Reid Spencerb83eb642006-10-20 07:07:24 +00002061 uint64_t SqrtValV = SqrtVal->getZExtValue();
Chris Lattner219c1412004-10-25 18:40:08 +00002062 uint64_t SqrtValV2 = (uint64_t)sqrt((double)SqrtValV);
Chris Lattner53e677a2004-04-02 20:23:17 +00002063 // The square root might not be precise for arbitrary 64-bit integer
2064 // values. Do some sanity checks to ensure it's correct.
2065 if (SqrtValV2*SqrtValV2 > SqrtValV ||
2066 (SqrtValV2+1)*(SqrtValV2+1) <= SqrtValV) {
2067 SCEV *CNC = new SCEVCouldNotCompute();
2068 return std::make_pair(CNC, CNC);
2069 }
2070
Reid Spencerb83eb642006-10-20 07:07:24 +00002071 SqrtVal = ConstantInt::get(Type::ULongTy, SqrtValV2);
Chris Lattner53e677a2004-04-02 20:23:17 +00002072 SqrtTerm = ConstantExpr::getCast(SqrtVal, SqrtTerm->getType());
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002073
Chris Lattner53e677a2004-04-02 20:23:17 +00002074 Constant *NegB = ConstantExpr::getNeg(B);
2075 Constant *TwoA = ConstantExpr::getMul(A, Two);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002076
Chris Lattner53e677a2004-04-02 20:23:17 +00002077 // The divisions must be performed as signed divisions.
2078 const Type *SignedTy = NegB->getType()->getSignedVersion();
2079 NegB = ConstantExpr::getCast(NegB, SignedTy);
2080 TwoA = ConstantExpr::getCast(TwoA, SignedTy);
2081 SqrtTerm = ConstantExpr::getCast(SqrtTerm, SignedTy);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002082
Chris Lattner53e677a2004-04-02 20:23:17 +00002083 Constant *Solution1 =
Reid Spencer1628cec2006-10-26 06:15:43 +00002084 ConstantExpr::getSDiv(ConstantExpr::getAdd(NegB, SqrtTerm), TwoA);
Chris Lattner53e677a2004-04-02 20:23:17 +00002085 Constant *Solution2 =
Reid Spencer1628cec2006-10-26 06:15:43 +00002086 ConstantExpr::getSDiv(ConstantExpr::getSub(NegB, SqrtTerm), TwoA);
Chris Lattner53e677a2004-04-02 20:23:17 +00002087 return std::make_pair(SCEVUnknown::get(Solution1),
2088 SCEVUnknown::get(Solution2));
2089}
2090
2091/// HowFarToZero - Return the number of times a backedge comparing the specified
2092/// value to zero will execute. If not computable, return UnknownValue
2093SCEVHandle ScalarEvolutionsImpl::HowFarToZero(SCEV *V, const Loop *L) {
2094 // If the value is a constant
2095 if (SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
2096 // If the value is already zero, the branch will execute zero times.
2097 if (C->getValue()->isNullValue()) return C;
2098 return UnknownValue; // Otherwise it will loop infinitely.
2099 }
2100
2101 SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
2102 if (!AddRec || AddRec->getLoop() != L)
2103 return UnknownValue;
2104
2105 if (AddRec->isAffine()) {
2106 // If this is an affine expression the execution count of this branch is
2107 // equal to:
2108 //
2109 // (0 - Start/Step) iff Start % Step == 0
2110 //
2111 // Get the initial value for the loop.
2112 SCEVHandle Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
Chris Lattner4a2b23e2004-10-11 04:07:27 +00002113 if (isa<SCEVCouldNotCompute>(Start)) return UnknownValue;
Chris Lattner53e677a2004-04-02 20:23:17 +00002114 SCEVHandle Step = AddRec->getOperand(1);
2115
2116 Step = getSCEVAtScope(Step, L->getParentLoop());
2117
2118 // Figure out if Start % Step == 0.
2119 // FIXME: We should add DivExpr and RemExpr operations to our AST.
2120 if (SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step)) {
2121 if (StepC->getValue()->equalsInt(1)) // N % 1 == 0
Chris Lattnerbac5b462005-03-09 05:34:41 +00002122 return SCEV::getNegativeSCEV(Start); // 0 - Start/1 == -Start
Chris Lattner53e677a2004-04-02 20:23:17 +00002123 if (StepC->getValue()->isAllOnesValue()) // N % -1 == 0
2124 return Start; // 0 - Start/-1 == Start
2125
2126 // Check to see if Start is divisible by SC with no remainder.
2127 if (SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start)) {
2128 ConstantInt *StartCC = StartC->getValue();
2129 Constant *StartNegC = ConstantExpr::getNeg(StartCC);
Reid Spencer0a783f72006-11-02 01:53:59 +00002130 Constant *Rem = ConstantExpr::getSRem(StartNegC, StepC->getValue());
Chris Lattner53e677a2004-04-02 20:23:17 +00002131 if (Rem->isNullValue()) {
Reid Spencer1628cec2006-10-26 06:15:43 +00002132 Constant *Result =ConstantExpr::getSDiv(StartNegC,StepC->getValue());
Chris Lattner53e677a2004-04-02 20:23:17 +00002133 return SCEVUnknown::get(Result);
2134 }
2135 }
2136 }
2137 } else if (AddRec->isQuadratic() && AddRec->getType()->isInteger()) {
2138 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
2139 // the quadratic equation to solve it.
2140 std::pair<SCEVHandle,SCEVHandle> Roots = SolveQuadraticEquation(AddRec);
2141 SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
2142 SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
2143 if (R1) {
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00002144#if 0
Chris Lattner53e677a2004-04-02 20:23:17 +00002145 std::cerr << "HFTZ: " << *V << " - sol#1: " << *R1
2146 << " sol#2: " << *R2 << "\n";
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00002147#endif
Chris Lattner53e677a2004-04-02 20:23:17 +00002148 // Pick the smallest positive root value.
2149 assert(R1->getType()->isUnsigned()&&"Didn't canonicalize to unsigned?");
2150 if (ConstantBool *CB =
2151 dyn_cast<ConstantBool>(ConstantExpr::getSetLT(R1->getValue(),
2152 R2->getValue()))) {
Chris Lattner003cbf32006-09-28 23:36:21 +00002153 if (CB->getValue() == false)
Chris Lattner53e677a2004-04-02 20:23:17 +00002154 std::swap(R1, R2); // R1 is the minimum root now.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002155
Chris Lattner53e677a2004-04-02 20:23:17 +00002156 // We can only use this value if the chrec ends up with an exact zero
2157 // value at this index. When solving for "X*X != 5", for example, we
2158 // should not accept a root of 2.
2159 SCEVHandle Val = AddRec->evaluateAtIteration(R1);
2160 if (SCEVConstant *EvalVal = dyn_cast<SCEVConstant>(Val))
2161 if (EvalVal->getValue()->isNullValue())
2162 return R1; // We found a quadratic root!
2163 }
2164 }
2165 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002166
Chris Lattner53e677a2004-04-02 20:23:17 +00002167 return UnknownValue;
2168}
2169
2170/// HowFarToNonZero - Return the number of times a backedge checking the
2171/// specified value for nonzero will execute. If not computable, return
2172/// UnknownValue
2173SCEVHandle ScalarEvolutionsImpl::HowFarToNonZero(SCEV *V, const Loop *L) {
2174 // Loops that look like: while (X == 0) are very strange indeed. We don't
2175 // handle them yet except for the trivial case. This could be expanded in the
2176 // future as needed.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002177
Chris Lattner53e677a2004-04-02 20:23:17 +00002178 // If the value is a constant, check to see if it is known to be non-zero
2179 // already. If so, the backedge will execute zero times.
2180 if (SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
2181 Constant *Zero = Constant::getNullValue(C->getValue()->getType());
2182 Constant *NonZero = ConstantExpr::getSetNE(C->getValue(), Zero);
Chris Lattner003cbf32006-09-28 23:36:21 +00002183 if (NonZero == ConstantBool::getTrue())
Chris Lattner53e677a2004-04-02 20:23:17 +00002184 return getSCEV(Zero);
2185 return UnknownValue; // Otherwise it will loop infinitely.
2186 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002187
Chris Lattner53e677a2004-04-02 20:23:17 +00002188 // We could implement others, but I really doubt anyone writes loops like
2189 // this, and if they did, they would already be constant folded.
2190 return UnknownValue;
2191}
2192
Chris Lattnerdb25de42005-08-15 23:33:51 +00002193/// HowManyLessThans - Return the number of times a backedge containing the
2194/// specified less-than comparison will execute. If not computable, return
2195/// UnknownValue.
2196SCEVHandle ScalarEvolutionsImpl::
2197HowManyLessThans(SCEV *LHS, SCEV *RHS, const Loop *L) {
2198 // Only handle: "ADDREC < LoopInvariant".
2199 if (!RHS->isLoopInvariant(L)) return UnknownValue;
2200
2201 SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS);
2202 if (!AddRec || AddRec->getLoop() != L)
2203 return UnknownValue;
2204
2205 if (AddRec->isAffine()) {
2206 // FORNOW: We only support unit strides.
2207 SCEVHandle One = SCEVUnknown::getIntegerSCEV(1, RHS->getType());
2208 if (AddRec->getOperand(1) != One)
2209 return UnknownValue;
2210
2211 // The number of iterations for "[n,+,1] < m", is m-n. However, we don't
2212 // know that m is >= n on input to the loop. If it is, the condition return
2213 // true zero times. What we really should return, for full generality, is
2214 // SMAX(0, m-n). Since we cannot check this, we will instead check for a
2215 // canonical loop form: most do-loops will have a check that dominates the
2216 // loop, that only enters the loop if [n-1]<m. If we can find this check,
2217 // we know that the SMAX will evaluate to m-n, because we know that m >= n.
2218
2219 // Search for the check.
2220 BasicBlock *Preheader = L->getLoopPreheader();
2221 BasicBlock *PreheaderDest = L->getHeader();
2222 if (Preheader == 0) return UnknownValue;
2223
2224 BranchInst *LoopEntryPredicate =
2225 dyn_cast<BranchInst>(Preheader->getTerminator());
2226 if (!LoopEntryPredicate) return UnknownValue;
2227
2228 // This might be a critical edge broken out. If the loop preheader ends in
2229 // an unconditional branch to the loop, check to see if the preheader has a
2230 // single predecessor, and if so, look for its terminator.
2231 while (LoopEntryPredicate->isUnconditional()) {
2232 PreheaderDest = Preheader;
2233 Preheader = Preheader->getSinglePredecessor();
2234 if (!Preheader) return UnknownValue; // Multiple preds.
2235
2236 LoopEntryPredicate =
2237 dyn_cast<BranchInst>(Preheader->getTerminator());
2238 if (!LoopEntryPredicate) return UnknownValue;
2239 }
2240
2241 // Now that we found a conditional branch that dominates the loop, check to
2242 // see if it is the comparison we are looking for.
2243 SetCondInst *SCI =dyn_cast<SetCondInst>(LoopEntryPredicate->getCondition());
2244 if (!SCI) return UnknownValue;
2245 Value *PreCondLHS = SCI->getOperand(0);
2246 Value *PreCondRHS = SCI->getOperand(1);
2247 Instruction::BinaryOps Cond;
2248 if (LoopEntryPredicate->getSuccessor(0) == PreheaderDest)
2249 Cond = SCI->getOpcode();
2250 else
2251 Cond = SCI->getInverseCondition();
2252
2253 switch (Cond) {
2254 case Instruction::SetGT:
2255 std::swap(PreCondLHS, PreCondRHS);
2256 Cond = Instruction::SetLT;
2257 // Fall Through.
2258 case Instruction::SetLT:
2259 if (PreCondLHS->getType()->isInteger() &&
2260 PreCondLHS->getType()->isSigned()) {
2261 if (RHS != getSCEV(PreCondRHS))
2262 return UnknownValue; // Not a comparison against 'm'.
2263
2264 if (SCEV::getMinusSCEV(AddRec->getOperand(0), One)
2265 != getSCEV(PreCondLHS))
2266 return UnknownValue; // Not a comparison against 'n-1'.
2267 break;
2268 } else {
2269 return UnknownValue;
2270 }
2271 default: break;
2272 }
2273
2274 //std::cerr << "Computed Loop Trip Count as: " <<
2275 // *SCEV::getMinusSCEV(RHS, AddRec->getOperand(0)) << "\n";
2276 return SCEV::getMinusSCEV(RHS, AddRec->getOperand(0));
2277 }
2278
2279 return UnknownValue;
2280}
2281
Chris Lattner53e677a2004-04-02 20:23:17 +00002282/// getNumIterationsInRange - Return the number of iterations of this loop that
2283/// produce values in the specified constant range. Another way of looking at
2284/// this is that it returns the first iteration number where the value is not in
2285/// the condition, thus computing the exit count. If the iteration count can't
2286/// be computed, an instance of SCEVCouldNotCompute is returned.
2287SCEVHandle SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range) const {
2288 if (Range.isFullSet()) // Infinite loop.
2289 return new SCEVCouldNotCompute();
2290
2291 // If the start is a non-zero constant, shift the range to simplify things.
2292 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
2293 if (!SC->getValue()->isNullValue()) {
2294 std::vector<SCEVHandle> Operands(op_begin(), op_end());
Chris Lattnerb06432c2004-04-23 21:29:03 +00002295 Operands[0] = SCEVUnknown::getIntegerSCEV(0, SC->getType());
Chris Lattner53e677a2004-04-02 20:23:17 +00002296 SCEVHandle Shifted = SCEVAddRecExpr::get(Operands, getLoop());
2297 if (SCEVAddRecExpr *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted))
2298 return ShiftedAddRec->getNumIterationsInRange(
2299 Range.subtract(SC->getValue()));
2300 // This is strange and shouldn't happen.
2301 return new SCEVCouldNotCompute();
2302 }
2303
2304 // The only time we can solve this is when we have all constant indices.
2305 // Otherwise, we cannot determine the overflow conditions.
2306 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
2307 if (!isa<SCEVConstant>(getOperand(i)))
2308 return new SCEVCouldNotCompute();
2309
2310
2311 // Okay at this point we know that all elements of the chrec are constants and
2312 // that the start element is zero.
2313
2314 // First check to see if the range contains zero. If not, the first
2315 // iteration exits.
2316 ConstantInt *Zero = ConstantInt::get(getType(), 0);
2317 if (!Range.contains(Zero)) return SCEVConstant::get(Zero);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002318
Chris Lattner53e677a2004-04-02 20:23:17 +00002319 if (isAffine()) {
2320 // If this is an affine expression then we have this situation:
2321 // Solve {0,+,A} in Range === Ax in Range
2322
2323 // Since we know that zero is in the range, we know that the upper value of
2324 // the range must be the first possible exit value. Also note that we
2325 // already checked for a full range.
2326 ConstantInt *Upper = cast<ConstantInt>(Range.getUpper());
2327 ConstantInt *A = cast<SCEVConstant>(getOperand(1))->getValue();
2328 ConstantInt *One = ConstantInt::get(getType(), 1);
2329
2330 // The exit value should be (Upper+A-1)/A.
2331 Constant *ExitValue = Upper;
2332 if (A != One) {
2333 ExitValue = ConstantExpr::getSub(ConstantExpr::getAdd(Upper, A), One);
Reid Spencer1628cec2006-10-26 06:15:43 +00002334 ExitValue = ConstantExpr::getSDiv(ExitValue, A);
Chris Lattner53e677a2004-04-02 20:23:17 +00002335 }
2336 assert(isa<ConstantInt>(ExitValue) &&
2337 "Constant folding of integers not implemented?");
2338
2339 // Evaluate at the exit value. If we really did fall out of the valid
2340 // range, then we computed our trip count, otherwise wrap around or other
2341 // things must have happened.
2342 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue);
2343 if (Range.contains(Val))
2344 return new SCEVCouldNotCompute(); // Something strange happened
2345
2346 // Ensure that the previous value is in the range. This is a sanity check.
2347 assert(Range.contains(EvaluateConstantChrecAtConstant(this,
2348 ConstantExpr::getSub(ExitValue, One))) &&
2349 "Linear scev computation is off in a bad way!");
2350 return SCEVConstant::get(cast<ConstantInt>(ExitValue));
2351 } else if (isQuadratic()) {
2352 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
2353 // quadratic equation to solve it. To do this, we must frame our problem in
2354 // terms of figuring out when zero is crossed, instead of when
2355 // Range.getUpper() is crossed.
2356 std::vector<SCEVHandle> NewOps(op_begin(), op_end());
Chris Lattnerbac5b462005-03-09 05:34:41 +00002357 NewOps[0] = SCEV::getNegativeSCEV(SCEVUnknown::get(Range.getUpper()));
Chris Lattner53e677a2004-04-02 20:23:17 +00002358 SCEVHandle NewAddRec = SCEVAddRecExpr::get(NewOps, getLoop());
2359
2360 // Next, solve the constructed addrec
2361 std::pair<SCEVHandle,SCEVHandle> Roots =
2362 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec));
2363 SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
2364 SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
2365 if (R1) {
2366 // Pick the smallest positive root value.
2367 assert(R1->getType()->isUnsigned() && "Didn't canonicalize to unsigned?");
2368 if (ConstantBool *CB =
2369 dyn_cast<ConstantBool>(ConstantExpr::getSetLT(R1->getValue(),
2370 R2->getValue()))) {
Chris Lattner003cbf32006-09-28 23:36:21 +00002371 if (CB->getValue() == false)
Chris Lattner53e677a2004-04-02 20:23:17 +00002372 std::swap(R1, R2); // R1 is the minimum root now.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002373
Chris Lattner53e677a2004-04-02 20:23:17 +00002374 // Make sure the root is not off by one. The returned iteration should
2375 // not be in the range, but the previous one should be. When solving
2376 // for "X*X < 5", for example, we should not return a root of 2.
2377 ConstantInt *R1Val = EvaluateConstantChrecAtConstant(this,
2378 R1->getValue());
2379 if (Range.contains(R1Val)) {
2380 // The next iteration must be out of the range...
2381 Constant *NextVal =
2382 ConstantExpr::getAdd(R1->getValue(),
2383 ConstantInt::get(R1->getType(), 1));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002384
Chris Lattner53e677a2004-04-02 20:23:17 +00002385 R1Val = EvaluateConstantChrecAtConstant(this, NextVal);
2386 if (!Range.contains(R1Val))
2387 return SCEVUnknown::get(NextVal);
2388 return new SCEVCouldNotCompute(); // Something strange happened
2389 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002390
Chris Lattner53e677a2004-04-02 20:23:17 +00002391 // If R1 was not in the range, then it is a good return value. Make
2392 // sure that R1-1 WAS in the range though, just in case.
2393 Constant *NextVal =
2394 ConstantExpr::getSub(R1->getValue(),
2395 ConstantInt::get(R1->getType(), 1));
2396 R1Val = EvaluateConstantChrecAtConstant(this, NextVal);
2397 if (Range.contains(R1Val))
2398 return R1;
2399 return new SCEVCouldNotCompute(); // Something strange happened
2400 }
2401 }
2402 }
2403
2404 // Fallback, if this is a general polynomial, figure out the progression
2405 // through brute force: evaluate until we find an iteration that fails the
2406 // test. This is likely to be slow, but getting an accurate trip count is
2407 // incredibly important, we will be able to simplify the exit test a lot, and
2408 // we are almost guaranteed to get a trip count in this case.
2409 ConstantInt *TestVal = ConstantInt::get(getType(), 0);
2410 ConstantInt *One = ConstantInt::get(getType(), 1);
2411 ConstantInt *EndVal = TestVal; // Stop when we wrap around.
2412 do {
2413 ++NumBruteForceEvaluations;
2414 SCEVHandle Val = evaluateAtIteration(SCEVConstant::get(TestVal));
2415 if (!isa<SCEVConstant>(Val)) // This shouldn't happen.
2416 return new SCEVCouldNotCompute();
2417
2418 // Check to see if we found the value!
2419 if (!Range.contains(cast<SCEVConstant>(Val)->getValue()))
2420 return SCEVConstant::get(TestVal);
2421
2422 // Increment to test the next index.
2423 TestVal = cast<ConstantInt>(ConstantExpr::getAdd(TestVal, One));
2424 } while (TestVal != EndVal);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002425
Chris Lattner53e677a2004-04-02 20:23:17 +00002426 return new SCEVCouldNotCompute();
2427}
2428
2429
2430
2431//===----------------------------------------------------------------------===//
2432// ScalarEvolution Class Implementation
2433//===----------------------------------------------------------------------===//
2434
2435bool ScalarEvolution::runOnFunction(Function &F) {
2436 Impl = new ScalarEvolutionsImpl(F, getAnalysis<LoopInfo>());
2437 return false;
2438}
2439
2440void ScalarEvolution::releaseMemory() {
2441 delete (ScalarEvolutionsImpl*)Impl;
2442 Impl = 0;
2443}
2444
2445void ScalarEvolution::getAnalysisUsage(AnalysisUsage &AU) const {
2446 AU.setPreservesAll();
Chris Lattner53e677a2004-04-02 20:23:17 +00002447 AU.addRequiredTransitive<LoopInfo>();
2448}
2449
2450SCEVHandle ScalarEvolution::getSCEV(Value *V) const {
2451 return ((ScalarEvolutionsImpl*)Impl)->getSCEV(V);
2452}
2453
Chris Lattnera0740fb2005-08-09 23:36:33 +00002454/// hasSCEV - Return true if the SCEV for this value has already been
2455/// computed.
2456bool ScalarEvolution::hasSCEV(Value *V) const {
Chris Lattner05bd3742005-08-10 00:59:40 +00002457 return ((ScalarEvolutionsImpl*)Impl)->hasSCEV(V);
Chris Lattnera0740fb2005-08-09 23:36:33 +00002458}
2459
2460
2461/// setSCEV - Insert the specified SCEV into the map of current SCEVs for
2462/// the specified value.
2463void ScalarEvolution::setSCEV(Value *V, const SCEVHandle &H) {
2464 ((ScalarEvolutionsImpl*)Impl)->setSCEV(V, H);
2465}
2466
2467
Chris Lattner53e677a2004-04-02 20:23:17 +00002468SCEVHandle ScalarEvolution::getIterationCount(const Loop *L) const {
2469 return ((ScalarEvolutionsImpl*)Impl)->getIterationCount(L);
2470}
2471
2472bool ScalarEvolution::hasLoopInvariantIterationCount(const Loop *L) const {
2473 return !isa<SCEVCouldNotCompute>(getIterationCount(L));
2474}
2475
2476SCEVHandle ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) const {
2477 return ((ScalarEvolutionsImpl*)Impl)->getSCEVAtScope(getSCEV(V), L);
2478}
2479
2480void ScalarEvolution::deleteInstructionFromRecords(Instruction *I) const {
2481 return ((ScalarEvolutionsImpl*)Impl)->deleteInstructionFromRecords(I);
2482}
2483
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002484static void PrintLoopInfo(std::ostream &OS, const ScalarEvolution *SE,
Chris Lattner53e677a2004-04-02 20:23:17 +00002485 const Loop *L) {
2486 // Print all inner loops first
2487 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
2488 PrintLoopInfo(OS, SE, *I);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002489
Chris Lattner53e677a2004-04-02 20:23:17 +00002490 std::cerr << "Loop " << L->getHeader()->getName() << ": ";
Chris Lattnerf1ab4b42004-04-18 22:14:10 +00002491
2492 std::vector<BasicBlock*> ExitBlocks;
2493 L->getExitBlocks(ExitBlocks);
2494 if (ExitBlocks.size() != 1)
Chris Lattner53e677a2004-04-02 20:23:17 +00002495 std::cerr << "<multiple exits> ";
2496
2497 if (SE->hasLoopInvariantIterationCount(L)) {
2498 std::cerr << *SE->getIterationCount(L) << " iterations! ";
2499 } else {
2500 std::cerr << "Unpredictable iteration count. ";
2501 }
2502
2503 std::cerr << "\n";
2504}
2505
Reid Spencerce9653c2004-12-07 04:03:45 +00002506void ScalarEvolution::print(std::ostream &OS, const Module* ) const {
Chris Lattner53e677a2004-04-02 20:23:17 +00002507 Function &F = ((ScalarEvolutionsImpl*)Impl)->F;
2508 LoopInfo &LI = ((ScalarEvolutionsImpl*)Impl)->LI;
2509
2510 OS << "Classifying expressions for: " << F.getName() << "\n";
2511 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
Chris Lattner6ffe5512004-04-27 15:13:33 +00002512 if (I->getType()->isInteger()) {
2513 OS << *I;
Chris Lattner53e677a2004-04-02 20:23:17 +00002514 OS << " --> ";
Chris Lattner6ffe5512004-04-27 15:13:33 +00002515 SCEVHandle SV = getSCEV(&*I);
Chris Lattner53e677a2004-04-02 20:23:17 +00002516 SV->print(OS);
2517 OS << "\t\t";
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002518
Chris Lattner6ffe5512004-04-27 15:13:33 +00002519 if ((*I).getType()->isIntegral()) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002520 ConstantRange Bounds = SV->getValueRange();
2521 if (!Bounds.isFullSet())
2522 OS << "Bounds: " << Bounds << " ";
2523 }
2524
Chris Lattner6ffe5512004-04-27 15:13:33 +00002525 if (const Loop *L = LI.getLoopFor((*I).getParent())) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002526 OS << "Exits: ";
Chris Lattner6ffe5512004-04-27 15:13:33 +00002527 SCEVHandle ExitValue = getSCEVAtScope(&*I, L->getParentLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00002528 if (isa<SCEVCouldNotCompute>(ExitValue)) {
2529 OS << "<<Unknown>>";
2530 } else {
2531 OS << *ExitValue;
2532 }
2533 }
2534
2535
2536 OS << "\n";
2537 }
2538
2539 OS << "Determining loop execution counts for: " << F.getName() << "\n";
2540 for (LoopInfo::iterator I = LI.begin(), E = LI.end(); I != E; ++I)
2541 PrintLoopInfo(OS, this, *I);
2542}
2543