blob: 87232b371cec8c3c79e7820b1fdb8ce9a39df64e [file] [log] [blame]
Chris Lattner53e677a2004-04-02 20:23:17 +00001//===- ScalarEvolution.cpp - Scalar Evolution Analysis ----------*- C++ -*-===//
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002//
Chris Lattner53e677a2004-04-02 20:23:17 +00003// The LLVM Compiler Infrastructure
4//
5// This file was developed by the LLVM research group and is distributed under
6// the University of Illinois Open Source License. See LICENSE.TXT for details.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00007//
Chris Lattner53e677a2004-04-02 20:23:17 +00008//===----------------------------------------------------------------------===//
9//
10// This file contains the implementation of the scalar evolution analysis
11// engine, which is used primarily to analyze expressions involving induction
12// variables in loops.
13//
14// There are several aspects to this library. First is the representation of
15// scalar expressions, which are represented as subclasses of the SCEV class.
16// These classes are used to represent certain types of subexpressions that we
17// can handle. These classes are reference counted, managed by the SCEVHandle
18// class. We only create one SCEV of a particular shape, so pointer-comparisons
19// for equality are legal.
20//
21// One important aspect of the SCEV objects is that they are never cyclic, even
22// if there is a cycle in the dataflow for an expression (ie, a PHI node). If
23// the PHI node is one of the idioms that we can represent (e.g., a polynomial
24// recurrence) then we represent it directly as a recurrence node, otherwise we
25// represent it as a SCEVUnknown node.
26//
27// In addition to being able to represent expressions of various types, we also
28// have folders that are used to build the *canonical* representation for a
29// particular expression. These folders are capable of using a variety of
30// rewrite rules to simplify the expressions.
Misha Brukman2b37d7c2005-04-21 21:13:18 +000031//
Chris Lattner53e677a2004-04-02 20:23:17 +000032// Once the folders are defined, we can implement the more interesting
33// higher-level code, such as the code that recognizes PHI nodes of various
34// types, computes the execution count of a loop, etc.
35//
Chris Lattner53e677a2004-04-02 20:23:17 +000036// TODO: We should use these routines and value representations to implement
37// dependence analysis!
38//
39//===----------------------------------------------------------------------===//
40//
41// There are several good references for the techniques used in this analysis.
42//
43// Chains of recurrences -- a method to expedite the evaluation
44// of closed-form functions
45// Olaf Bachmann, Paul S. Wang, Eugene V. Zima
46//
47// On computational properties of chains of recurrences
48// Eugene V. Zima
49//
50// Symbolic Evaluation of Chains of Recurrences for Loop Optimization
51// Robert A. van Engelen
52//
53// Efficient Symbolic Analysis for Optimizing Compilers
54// Robert A. van Engelen
55//
56// Using the chains of recurrences algebra for data dependence testing and
57// induction variable substitution
58// MS Thesis, Johnie Birch
59//
60//===----------------------------------------------------------------------===//
61
Chris Lattner0a7f98c2004-04-15 15:07:24 +000062#include "llvm/Analysis/ScalarEvolutionExpressions.h"
Chris Lattner53e677a2004-04-02 20:23:17 +000063#include "llvm/Constants.h"
64#include "llvm/DerivedTypes.h"
Chris Lattner673e02b2004-10-12 01:49:27 +000065#include "llvm/GlobalVariable.h"
Chris Lattner53e677a2004-04-02 20:23:17 +000066#include "llvm/Instructions.h"
John Criswella1156432005-10-27 15:54:34 +000067#include "llvm/Analysis/ConstantFolding.h"
Chris Lattner53e677a2004-04-02 20:23:17 +000068#include "llvm/Analysis/LoopInfo.h"
69#include "llvm/Assembly/Writer.h"
70#include "llvm/Transforms/Scalar.h"
71#include "llvm/Support/CFG.h"
Chris Lattner95255282006-06-28 23:17:24 +000072#include "llvm/Support/CommandLine.h"
Chris Lattnerb3364092006-10-04 21:49:37 +000073#include "llvm/Support/Compiler.h"
Chris Lattner53e677a2004-04-02 20:23:17 +000074#include "llvm/Support/ConstantRange.h"
75#include "llvm/Support/InstIterator.h"
Chris Lattnerb3364092006-10-04 21:49:37 +000076#include "llvm/Support/ManagedStatic.h"
Bill Wendling6f81b512006-11-28 22:46:12 +000077#include "llvm/Support/Streams.h"
Reid Spencer551ccae2004-09-01 22:55:40 +000078#include "llvm/ADT/Statistic.h"
Bill Wendling6f81b512006-11-28 22:46:12 +000079#include <ostream>
Alkis Evlogimenos20aa4742004-09-03 18:19:51 +000080#include <algorithm>
Jeff Cohen97af7512006-12-02 02:22:01 +000081#include <cmath>
Chris Lattner53e677a2004-04-02 20:23:17 +000082using namespace llvm;
83
84namespace {
Chris Lattner5d8925c2006-08-27 22:30:17 +000085 RegisterPass<ScalarEvolution>
Chris Lattner45a1cf82004-04-19 03:42:32 +000086 R("scalar-evolution", "Scalar Evolution Analysis");
Chris Lattner53e677a2004-04-02 20:23:17 +000087
88 Statistic<>
89 NumBruteForceEvaluations("scalar-evolution",
Chris Lattner673e02b2004-10-12 01:49:27 +000090 "Number of brute force evaluations needed to "
91 "calculate high-order polynomial exit values");
92 Statistic<>
93 NumArrayLenItCounts("scalar-evolution",
94 "Number of trip counts computed with array length");
Chris Lattner53e677a2004-04-02 20:23:17 +000095 Statistic<>
96 NumTripCountsComputed("scalar-evolution",
97 "Number of loops with predictable loop counts");
98 Statistic<>
99 NumTripCountsNotComputed("scalar-evolution",
100 "Number of loops without predictable loop counts");
Chris Lattner7980fb92004-04-17 18:36:24 +0000101 Statistic<>
102 NumBruteForceTripCountsComputed("scalar-evolution",
103 "Number of loops with trip counts computed by force");
104
105 cl::opt<unsigned>
106 MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden,
Chris Lattnerbed21de2005-09-28 22:30:58 +0000107 cl::desc("Maximum number of iterations SCEV will "
108 "symbolically execute a constant derived loop"),
Chris Lattner7980fb92004-04-17 18:36:24 +0000109 cl::init(100));
Chris Lattner53e677a2004-04-02 20:23:17 +0000110}
111
112//===----------------------------------------------------------------------===//
113// SCEV class definitions
114//===----------------------------------------------------------------------===//
115
116//===----------------------------------------------------------------------===//
117// Implementation of the SCEV class.
118//
Chris Lattner53e677a2004-04-02 20:23:17 +0000119SCEV::~SCEV() {}
120void SCEV::dump() const {
Bill Wendling6f81b512006-11-28 22:46:12 +0000121 print(llvm_cerr);
Chris Lattner53e677a2004-04-02 20:23:17 +0000122}
123
124/// getValueRange - Return the tightest constant bounds that this value is
125/// known to have. This method is only valid on integer SCEV objects.
126ConstantRange SCEV::getValueRange() const {
127 const Type *Ty = getType();
128 assert(Ty->isInteger() && "Can't get range for a non-integer SCEV!");
129 Ty = Ty->getUnsignedVersion();
130 // Default to a full range if no better information is available.
131 return ConstantRange(getType());
132}
133
134
135SCEVCouldNotCompute::SCEVCouldNotCompute() : SCEV(scCouldNotCompute) {}
136
137bool SCEVCouldNotCompute::isLoopInvariant(const Loop *L) const {
138 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
Misha Brukmanbb2aff12004-04-05 19:00:46 +0000139 return false;
Chris Lattner53e677a2004-04-02 20:23:17 +0000140}
141
142const Type *SCEVCouldNotCompute::getType() const {
143 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
Misha Brukmanbb2aff12004-04-05 19:00:46 +0000144 return 0;
Chris Lattner53e677a2004-04-02 20:23:17 +0000145}
146
147bool SCEVCouldNotCompute::hasComputableLoopEvolution(const Loop *L) const {
148 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
149 return false;
150}
151
Chris Lattner4dc534c2005-02-13 04:37:18 +0000152SCEVHandle SCEVCouldNotCompute::
153replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
154 const SCEVHandle &Conc) const {
155 return this;
156}
157
Chris Lattner53e677a2004-04-02 20:23:17 +0000158void SCEVCouldNotCompute::print(std::ostream &OS) const {
159 OS << "***COULDNOTCOMPUTE***";
160}
161
162bool SCEVCouldNotCompute::classof(const SCEV *S) {
163 return S->getSCEVType() == scCouldNotCompute;
164}
165
166
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000167// SCEVConstants - Only allow the creation of one SCEVConstant for any
168// particular value. Don't use a SCEVHandle here, or else the object will
169// never be deleted!
Chris Lattnerb3364092006-10-04 21:49:37 +0000170static ManagedStatic<std::map<ConstantInt*, SCEVConstant*> > SCEVConstants;
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000171
Chris Lattner53e677a2004-04-02 20:23:17 +0000172
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000173SCEVConstant::~SCEVConstant() {
Chris Lattnerb3364092006-10-04 21:49:37 +0000174 SCEVConstants->erase(V);
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000175}
Chris Lattner53e677a2004-04-02 20:23:17 +0000176
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000177SCEVHandle SCEVConstant::get(ConstantInt *V) {
178 // Make sure that SCEVConstant instances are all unsigned.
179 if (V->getType()->isSigned()) {
180 const Type *NewTy = V->getType()->getUnsignedVersion();
Reid Spencerb83eb642006-10-20 07:07:24 +0000181 V = cast<ConstantInt>(ConstantExpr::getCast(V, NewTy));
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000182 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000183
Chris Lattnerb3364092006-10-04 21:49:37 +0000184 SCEVConstant *&R = (*SCEVConstants)[V];
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000185 if (R == 0) R = new SCEVConstant(V);
186 return R;
187}
Chris Lattner53e677a2004-04-02 20:23:17 +0000188
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000189ConstantRange SCEVConstant::getValueRange() const {
190 return ConstantRange(V);
191}
Chris Lattner53e677a2004-04-02 20:23:17 +0000192
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000193const Type *SCEVConstant::getType() const { return V->getType(); }
Chris Lattner53e677a2004-04-02 20:23:17 +0000194
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000195void SCEVConstant::print(std::ostream &OS) const {
196 WriteAsOperand(OS, V, false);
197}
Chris Lattner53e677a2004-04-02 20:23:17 +0000198
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000199// SCEVTruncates - Only allow the creation of one SCEVTruncateExpr for any
200// particular input. Don't use a SCEVHandle here, or else the object will
201// never be deleted!
Chris Lattnerb3364092006-10-04 21:49:37 +0000202static ManagedStatic<std::map<std::pair<SCEV*, const Type*>,
203 SCEVTruncateExpr*> > SCEVTruncates;
Chris Lattner53e677a2004-04-02 20:23:17 +0000204
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000205SCEVTruncateExpr::SCEVTruncateExpr(const SCEVHandle &op, const Type *ty)
206 : SCEV(scTruncate), Op(op), Ty(ty) {
207 assert(Op->getType()->isInteger() && Ty->isInteger() &&
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000208 "Cannot truncate non-integer value!");
209 assert(Op->getType()->getPrimitiveSize() > Ty->getPrimitiveSize() &&
210 "This is not a truncating conversion!");
211}
Chris Lattner53e677a2004-04-02 20:23:17 +0000212
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000213SCEVTruncateExpr::~SCEVTruncateExpr() {
Chris Lattnerb3364092006-10-04 21:49:37 +0000214 SCEVTruncates->erase(std::make_pair(Op, Ty));
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000215}
Chris Lattner53e677a2004-04-02 20:23:17 +0000216
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000217ConstantRange SCEVTruncateExpr::getValueRange() const {
218 return getOperand()->getValueRange().truncate(getType());
219}
Chris Lattner53e677a2004-04-02 20:23:17 +0000220
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000221void SCEVTruncateExpr::print(std::ostream &OS) const {
222 OS << "(truncate " << *Op << " to " << *Ty << ")";
223}
224
225// SCEVZeroExtends - Only allow the creation of one SCEVZeroExtendExpr for any
226// particular input. Don't use a SCEVHandle here, or else the object will never
227// be deleted!
Chris Lattnerb3364092006-10-04 21:49:37 +0000228static ManagedStatic<std::map<std::pair<SCEV*, const Type*>,
229 SCEVZeroExtendExpr*> > SCEVZeroExtends;
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000230
231SCEVZeroExtendExpr::SCEVZeroExtendExpr(const SCEVHandle &op, const Type *ty)
Reid Spencer48d8a702006-11-01 21:53:12 +0000232 : SCEV(scZeroExtend), Op(op), Ty(ty) {
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000233 assert(Op->getType()->isInteger() && Ty->isInteger() &&
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000234 "Cannot zero extend non-integer value!");
235 assert(Op->getType()->getPrimitiveSize() < Ty->getPrimitiveSize() &&
236 "This is not an extending conversion!");
237}
238
239SCEVZeroExtendExpr::~SCEVZeroExtendExpr() {
Chris Lattnerb3364092006-10-04 21:49:37 +0000240 SCEVZeroExtends->erase(std::make_pair(Op, Ty));
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000241}
242
243ConstantRange SCEVZeroExtendExpr::getValueRange() const {
244 return getOperand()->getValueRange().zeroExtend(getType());
245}
246
247void SCEVZeroExtendExpr::print(std::ostream &OS) const {
248 OS << "(zeroextend " << *Op << " to " << *Ty << ")";
249}
250
251// SCEVCommExprs - Only allow the creation of one SCEVCommutativeExpr for any
252// particular input. Don't use a SCEVHandle here, or else the object will never
253// be deleted!
Chris Lattnerb3364092006-10-04 21:49:37 +0000254static ManagedStatic<std::map<std::pair<unsigned, std::vector<SCEV*> >,
255 SCEVCommutativeExpr*> > SCEVCommExprs;
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000256
257SCEVCommutativeExpr::~SCEVCommutativeExpr() {
Chris Lattnerb3364092006-10-04 21:49:37 +0000258 SCEVCommExprs->erase(std::make_pair(getSCEVType(),
259 std::vector<SCEV*>(Operands.begin(),
260 Operands.end())));
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000261}
262
263void SCEVCommutativeExpr::print(std::ostream &OS) const {
264 assert(Operands.size() > 1 && "This plus expr shouldn't exist!");
265 const char *OpStr = getOperationStr();
266 OS << "(" << *Operands[0];
267 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
268 OS << OpStr << *Operands[i];
269 OS << ")";
270}
271
Chris Lattner4dc534c2005-02-13 04:37:18 +0000272SCEVHandle SCEVCommutativeExpr::
273replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
274 const SCEVHandle &Conc) const {
275 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
276 SCEVHandle H = getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc);
277 if (H != getOperand(i)) {
278 std::vector<SCEVHandle> NewOps;
279 NewOps.reserve(getNumOperands());
280 for (unsigned j = 0; j != i; ++j)
281 NewOps.push_back(getOperand(j));
282 NewOps.push_back(H);
283 for (++i; i != e; ++i)
284 NewOps.push_back(getOperand(i)->
285 replaceSymbolicValuesWithConcrete(Sym, Conc));
286
287 if (isa<SCEVAddExpr>(this))
288 return SCEVAddExpr::get(NewOps);
289 else if (isa<SCEVMulExpr>(this))
290 return SCEVMulExpr::get(NewOps);
291 else
292 assert(0 && "Unknown commutative expr!");
293 }
294 }
295 return this;
296}
297
298
Chris Lattner60a05cc2006-04-01 04:48:52 +0000299// SCEVSDivs - Only allow the creation of one SCEVSDivExpr for any particular
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000300// input. Don't use a SCEVHandle here, or else the object will never be
301// deleted!
Chris Lattnerb3364092006-10-04 21:49:37 +0000302static ManagedStatic<std::map<std::pair<SCEV*, SCEV*>,
303 SCEVSDivExpr*> > SCEVSDivs;
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000304
Chris Lattner60a05cc2006-04-01 04:48:52 +0000305SCEVSDivExpr::~SCEVSDivExpr() {
Chris Lattnerb3364092006-10-04 21:49:37 +0000306 SCEVSDivs->erase(std::make_pair(LHS, RHS));
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000307}
308
Chris Lattner60a05cc2006-04-01 04:48:52 +0000309void SCEVSDivExpr::print(std::ostream &OS) const {
310 OS << "(" << *LHS << " /s " << *RHS << ")";
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000311}
312
Chris Lattner60a05cc2006-04-01 04:48:52 +0000313const Type *SCEVSDivExpr::getType() const {
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000314 const Type *Ty = LHS->getType();
Chris Lattner60a05cc2006-04-01 04:48:52 +0000315 if (Ty->isUnsigned()) Ty = Ty->getSignedVersion();
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000316 return Ty;
317}
318
319// SCEVAddRecExprs - Only allow the creation of one SCEVAddRecExpr for any
320// particular input. Don't use a SCEVHandle here, or else the object will never
321// be deleted!
Chris Lattnerb3364092006-10-04 21:49:37 +0000322static ManagedStatic<std::map<std::pair<const Loop *, std::vector<SCEV*> >,
323 SCEVAddRecExpr*> > SCEVAddRecExprs;
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000324
325SCEVAddRecExpr::~SCEVAddRecExpr() {
Chris Lattnerb3364092006-10-04 21:49:37 +0000326 SCEVAddRecExprs->erase(std::make_pair(L,
327 std::vector<SCEV*>(Operands.begin(),
328 Operands.end())));
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000329}
330
Chris Lattner4dc534c2005-02-13 04:37:18 +0000331SCEVHandle SCEVAddRecExpr::
332replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
333 const SCEVHandle &Conc) const {
334 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
335 SCEVHandle H = getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc);
336 if (H != getOperand(i)) {
337 std::vector<SCEVHandle> NewOps;
338 NewOps.reserve(getNumOperands());
339 for (unsigned j = 0; j != i; ++j)
340 NewOps.push_back(getOperand(j));
341 NewOps.push_back(H);
342 for (++i; i != e; ++i)
343 NewOps.push_back(getOperand(i)->
344 replaceSymbolicValuesWithConcrete(Sym, Conc));
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000345
Chris Lattner4dc534c2005-02-13 04:37:18 +0000346 return get(NewOps, L);
347 }
348 }
349 return this;
350}
351
352
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000353bool SCEVAddRecExpr::isLoopInvariant(const Loop *QueryLoop) const {
354 // This recurrence is invariant w.r.t to QueryLoop iff QueryLoop doesn't
Chris Lattnerff2006a2005-08-16 00:37:01 +0000355 // contain L and if the start is invariant.
356 return !QueryLoop->contains(L->getHeader()) &&
357 getOperand(0)->isLoopInvariant(QueryLoop);
Chris Lattner53e677a2004-04-02 20:23:17 +0000358}
359
360
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000361void SCEVAddRecExpr::print(std::ostream &OS) const {
362 OS << "{" << *Operands[0];
363 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
364 OS << ",+," << *Operands[i];
365 OS << "}<" << L->getHeader()->getName() + ">";
366}
Chris Lattner53e677a2004-04-02 20:23:17 +0000367
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000368// SCEVUnknowns - Only allow the creation of one SCEVUnknown for any particular
369// value. Don't use a SCEVHandle here, or else the object will never be
370// deleted!
Chris Lattnerb3364092006-10-04 21:49:37 +0000371static ManagedStatic<std::map<Value*, SCEVUnknown*> > SCEVUnknowns;
Chris Lattner53e677a2004-04-02 20:23:17 +0000372
Chris Lattnerb3364092006-10-04 21:49:37 +0000373SCEVUnknown::~SCEVUnknown() { SCEVUnknowns->erase(V); }
Chris Lattner53e677a2004-04-02 20:23:17 +0000374
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000375bool SCEVUnknown::isLoopInvariant(const Loop *L) const {
376 // All non-instruction values are loop invariant. All instructions are loop
377 // invariant if they are not contained in the specified loop.
378 if (Instruction *I = dyn_cast<Instruction>(V))
379 return !L->contains(I->getParent());
380 return true;
381}
Chris Lattner53e677a2004-04-02 20:23:17 +0000382
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000383const Type *SCEVUnknown::getType() const {
384 return V->getType();
385}
Chris Lattner53e677a2004-04-02 20:23:17 +0000386
Chris Lattner0a7f98c2004-04-15 15:07:24 +0000387void SCEVUnknown::print(std::ostream &OS) const {
388 WriteAsOperand(OS, V, false);
Chris Lattner53e677a2004-04-02 20:23:17 +0000389}
390
Chris Lattner8d741b82004-06-20 06:23:15 +0000391//===----------------------------------------------------------------------===//
392// SCEV Utilities
393//===----------------------------------------------------------------------===//
394
395namespace {
396 /// SCEVComplexityCompare - Return true if the complexity of the LHS is less
397 /// than the complexity of the RHS. This comparator is used to canonicalize
398 /// expressions.
Chris Lattner95255282006-06-28 23:17:24 +0000399 struct VISIBILITY_HIDDEN SCEVComplexityCompare {
Chris Lattner8d741b82004-06-20 06:23:15 +0000400 bool operator()(SCEV *LHS, SCEV *RHS) {
401 return LHS->getSCEVType() < RHS->getSCEVType();
402 }
403 };
404}
405
406/// GroupByComplexity - Given a list of SCEV objects, order them by their
407/// complexity, and group objects of the same complexity together by value.
408/// When this routine is finished, we know that any duplicates in the vector are
409/// consecutive and that complexity is monotonically increasing.
410///
411/// Note that we go take special precautions to ensure that we get determinstic
412/// results from this routine. In other words, we don't want the results of
413/// this to depend on where the addresses of various SCEV objects happened to
414/// land in memory.
415///
416static void GroupByComplexity(std::vector<SCEVHandle> &Ops) {
417 if (Ops.size() < 2) return; // Noop
418 if (Ops.size() == 2) {
419 // This is the common case, which also happens to be trivially simple.
420 // Special case it.
421 if (Ops[0]->getSCEVType() > Ops[1]->getSCEVType())
422 std::swap(Ops[0], Ops[1]);
423 return;
424 }
425
426 // Do the rough sort by complexity.
427 std::sort(Ops.begin(), Ops.end(), SCEVComplexityCompare());
428
429 // Now that we are sorted by complexity, group elements of the same
430 // complexity. Note that this is, at worst, N^2, but the vector is likely to
431 // be extremely short in practice. Note that we take this approach because we
432 // do not want to depend on the addresses of the objects we are grouping.
Chris Lattner2d584522004-06-20 17:01:44 +0000433 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
Chris Lattner8d741b82004-06-20 06:23:15 +0000434 SCEV *S = Ops[i];
435 unsigned Complexity = S->getSCEVType();
436
437 // If there are any objects of the same complexity and same value as this
438 // one, group them.
439 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
440 if (Ops[j] == S) { // Found a duplicate.
441 // Move it to immediately after i'th element.
442 std::swap(Ops[i+1], Ops[j]);
443 ++i; // no need to rescan it.
Chris Lattner541ad5e2004-06-20 20:32:16 +0000444 if (i == e-2) return; // Done!
Chris Lattner8d741b82004-06-20 06:23:15 +0000445 }
446 }
447 }
448}
449
Chris Lattner53e677a2004-04-02 20:23:17 +0000450
Chris Lattner53e677a2004-04-02 20:23:17 +0000451
452//===----------------------------------------------------------------------===//
453// Simple SCEV method implementations
454//===----------------------------------------------------------------------===//
455
456/// getIntegerSCEV - Given an integer or FP type, create a constant for the
457/// specified signed integer value and return a SCEV for the constant.
Chris Lattnerb06432c2004-04-23 21:29:03 +0000458SCEVHandle SCEVUnknown::getIntegerSCEV(int Val, const Type *Ty) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000459 Constant *C;
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000460 if (Val == 0)
Chris Lattner53e677a2004-04-02 20:23:17 +0000461 C = Constant::getNullValue(Ty);
462 else if (Ty->isFloatingPoint())
463 C = ConstantFP::get(Ty, Val);
464 else if (Ty->isSigned())
Reid Spencerb83eb642006-10-20 07:07:24 +0000465 C = ConstantInt::get(Ty, Val);
Chris Lattner53e677a2004-04-02 20:23:17 +0000466 else {
Reid Spencerb83eb642006-10-20 07:07:24 +0000467 C = ConstantInt::get(Ty->getSignedVersion(), Val);
Chris Lattner53e677a2004-04-02 20:23:17 +0000468 C = ConstantExpr::getCast(C, Ty);
469 }
470 return SCEVUnknown::get(C);
471}
472
473/// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion of the
474/// input value to the specified type. If the type must be extended, it is zero
475/// extended.
476static SCEVHandle getTruncateOrZeroExtend(const SCEVHandle &V, const Type *Ty) {
477 const Type *SrcTy = V->getType();
478 assert(SrcTy->isInteger() && Ty->isInteger() &&
479 "Cannot truncate or zero extend with non-integer arguments!");
480 if (SrcTy->getPrimitiveSize() == Ty->getPrimitiveSize())
481 return V; // No conversion
482 if (SrcTy->getPrimitiveSize() > Ty->getPrimitiveSize())
483 return SCEVTruncateExpr::get(V, Ty);
484 return SCEVZeroExtendExpr::get(V, Ty);
485}
486
487/// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V
488///
Chris Lattnerbac5b462005-03-09 05:34:41 +0000489SCEVHandle SCEV::getNegativeSCEV(const SCEVHandle &V) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000490 if (SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
491 return SCEVUnknown::get(ConstantExpr::getNeg(VC->getValue()));
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000492
Chris Lattnerb06432c2004-04-23 21:29:03 +0000493 return SCEVMulExpr::get(V, SCEVUnknown::getIntegerSCEV(-1, V->getType()));
Chris Lattner53e677a2004-04-02 20:23:17 +0000494}
495
496/// getMinusSCEV - Return a SCEV corresponding to LHS - RHS.
497///
Chris Lattnerbac5b462005-03-09 05:34:41 +0000498SCEVHandle SCEV::getMinusSCEV(const SCEVHandle &LHS, const SCEVHandle &RHS) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000499 // X - Y --> X + -Y
Chris Lattnerbac5b462005-03-09 05:34:41 +0000500 return SCEVAddExpr::get(LHS, SCEV::getNegativeSCEV(RHS));
Chris Lattner53e677a2004-04-02 20:23:17 +0000501}
502
503
Chris Lattner53e677a2004-04-02 20:23:17 +0000504/// PartialFact - Compute V!/(V-NumSteps)!
505static SCEVHandle PartialFact(SCEVHandle V, unsigned NumSteps) {
506 // Handle this case efficiently, it is common to have constant iteration
507 // counts while computing loop exit values.
508 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(V)) {
Reid Spencerb83eb642006-10-20 07:07:24 +0000509 uint64_t Val = SC->getValue()->getZExtValue();
Chris Lattner53e677a2004-04-02 20:23:17 +0000510 uint64_t Result = 1;
511 for (; NumSteps; --NumSteps)
512 Result *= Val-(NumSteps-1);
Reid Spencerb83eb642006-10-20 07:07:24 +0000513 Constant *Res = ConstantInt::get(Type::ULongTy, Result);
Chris Lattner53e677a2004-04-02 20:23:17 +0000514 return SCEVUnknown::get(ConstantExpr::getCast(Res, V->getType()));
515 }
516
517 const Type *Ty = V->getType();
518 if (NumSteps == 0)
Chris Lattnerb06432c2004-04-23 21:29:03 +0000519 return SCEVUnknown::getIntegerSCEV(1, Ty);
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000520
Chris Lattner53e677a2004-04-02 20:23:17 +0000521 SCEVHandle Result = V;
522 for (unsigned i = 1; i != NumSteps; ++i)
Chris Lattnerbac5b462005-03-09 05:34:41 +0000523 Result = SCEVMulExpr::get(Result, SCEV::getMinusSCEV(V,
Chris Lattnerb06432c2004-04-23 21:29:03 +0000524 SCEVUnknown::getIntegerSCEV(i, Ty)));
Chris Lattner53e677a2004-04-02 20:23:17 +0000525 return Result;
526}
527
528
529/// evaluateAtIteration - Return the value of this chain of recurrences at
530/// the specified iteration number. We can evaluate this recurrence by
531/// multiplying each element in the chain by the binomial coefficient
532/// corresponding to it. In other words, we can evaluate {A,+,B,+,C,+,D} as:
533///
534/// A*choose(It, 0) + B*choose(It, 1) + C*choose(It, 2) + D*choose(It, 3)
535///
536/// FIXME/VERIFY: I don't trust that this is correct in the face of overflow.
537/// Is the binomial equation safe using modular arithmetic??
538///
539SCEVHandle SCEVAddRecExpr::evaluateAtIteration(SCEVHandle It) const {
540 SCEVHandle Result = getStart();
541 int Divisor = 1;
542 const Type *Ty = It->getType();
543 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
544 SCEVHandle BC = PartialFact(It, i);
545 Divisor *= i;
Chris Lattner60a05cc2006-04-01 04:48:52 +0000546 SCEVHandle Val = SCEVSDivExpr::get(SCEVMulExpr::get(BC, getOperand(i)),
Chris Lattnerb06432c2004-04-23 21:29:03 +0000547 SCEVUnknown::getIntegerSCEV(Divisor,Ty));
Chris Lattner53e677a2004-04-02 20:23:17 +0000548 Result = SCEVAddExpr::get(Result, Val);
549 }
550 return Result;
551}
552
553
554//===----------------------------------------------------------------------===//
555// SCEV Expression folder implementations
556//===----------------------------------------------------------------------===//
557
558SCEVHandle SCEVTruncateExpr::get(const SCEVHandle &Op, const Type *Ty) {
559 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
560 return SCEVUnknown::get(ConstantExpr::getCast(SC->getValue(), Ty));
561
562 // If the input value is a chrec scev made out of constants, truncate
563 // all of the constants.
564 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
565 std::vector<SCEVHandle> Operands;
566 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
567 // FIXME: This should allow truncation of other expression types!
568 if (isa<SCEVConstant>(AddRec->getOperand(i)))
569 Operands.push_back(get(AddRec->getOperand(i), Ty));
570 else
571 break;
572 if (Operands.size() == AddRec->getNumOperands())
573 return SCEVAddRecExpr::get(Operands, AddRec->getLoop());
574 }
575
Chris Lattnerb3364092006-10-04 21:49:37 +0000576 SCEVTruncateExpr *&Result = (*SCEVTruncates)[std::make_pair(Op, Ty)];
Chris Lattner53e677a2004-04-02 20:23:17 +0000577 if (Result == 0) Result = new SCEVTruncateExpr(Op, Ty);
578 return Result;
579}
580
581SCEVHandle SCEVZeroExtendExpr::get(const SCEVHandle &Op, const Type *Ty) {
582 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
583 return SCEVUnknown::get(ConstantExpr::getCast(SC->getValue(), Ty));
584
585 // FIXME: If the input value is a chrec scev, and we can prove that the value
586 // did not overflow the old, smaller, value, we can zero extend all of the
587 // operands (often constants). This would allow analysis of something like
588 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
589
Chris Lattnerb3364092006-10-04 21:49:37 +0000590 SCEVZeroExtendExpr *&Result = (*SCEVZeroExtends)[std::make_pair(Op, Ty)];
Chris Lattner53e677a2004-04-02 20:23:17 +0000591 if (Result == 0) Result = new SCEVZeroExtendExpr(Op, Ty);
592 return Result;
593}
594
595// get - Get a canonical add expression, or something simpler if possible.
596SCEVHandle SCEVAddExpr::get(std::vector<SCEVHandle> &Ops) {
597 assert(!Ops.empty() && "Cannot get empty add!");
Chris Lattner627018b2004-04-07 16:16:11 +0000598 if (Ops.size() == 1) return Ops[0];
Chris Lattner53e677a2004-04-02 20:23:17 +0000599
600 // Sort by complexity, this groups all similar expression types together.
Chris Lattner8d741b82004-06-20 06:23:15 +0000601 GroupByComplexity(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +0000602
603 // If there are any constants, fold them together.
604 unsigned Idx = 0;
605 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
606 ++Idx;
Chris Lattner627018b2004-04-07 16:16:11 +0000607 assert(Idx < Ops.size());
Chris Lattner53e677a2004-04-02 20:23:17 +0000608 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
609 // We found two constants, fold them together!
610 Constant *Fold = ConstantExpr::getAdd(LHSC->getValue(), RHSC->getValue());
611 if (ConstantInt *CI = dyn_cast<ConstantInt>(Fold)) {
612 Ops[0] = SCEVConstant::get(CI);
613 Ops.erase(Ops.begin()+1); // Erase the folded element
614 if (Ops.size() == 1) return Ops[0];
Chris Lattner7ffc07d2005-02-26 18:50:19 +0000615 LHSC = cast<SCEVConstant>(Ops[0]);
Chris Lattner53e677a2004-04-02 20:23:17 +0000616 } else {
617 // If we couldn't fold the expression, move to the next constant. Note
618 // that this is impossible to happen in practice because we always
619 // constant fold constant ints to constant ints.
620 ++Idx;
621 }
622 }
623
624 // If we are left with a constant zero being added, strip it off.
625 if (cast<SCEVConstant>(Ops[0])->getValue()->isNullValue()) {
626 Ops.erase(Ops.begin());
627 --Idx;
628 }
629 }
630
Chris Lattner627018b2004-04-07 16:16:11 +0000631 if (Ops.size() == 1) return Ops[0];
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000632
Chris Lattner53e677a2004-04-02 20:23:17 +0000633 // Okay, check to see if the same value occurs in the operand list twice. If
634 // so, merge them together into an multiply expression. Since we sorted the
635 // list, these values are required to be adjacent.
636 const Type *Ty = Ops[0]->getType();
637 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
638 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
639 // Found a match, merge the two values into a multiply, and add any
640 // remaining values to the result.
Chris Lattnerb06432c2004-04-23 21:29:03 +0000641 SCEVHandle Two = SCEVUnknown::getIntegerSCEV(2, Ty);
Chris Lattner53e677a2004-04-02 20:23:17 +0000642 SCEVHandle Mul = SCEVMulExpr::get(Ops[i], Two);
643 if (Ops.size() == 2)
644 return Mul;
645 Ops.erase(Ops.begin()+i, Ops.begin()+i+2);
646 Ops.push_back(Mul);
647 return SCEVAddExpr::get(Ops);
648 }
649
650 // Okay, now we know the first non-constant operand. If there are add
651 // operands they would be next.
652 if (Idx < Ops.size()) {
653 bool DeletedAdd = false;
654 while (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
655 // If we have an add, expand the add operands onto the end of the operands
656 // list.
657 Ops.insert(Ops.end(), Add->op_begin(), Add->op_end());
658 Ops.erase(Ops.begin()+Idx);
659 DeletedAdd = true;
660 }
661
662 // If we deleted at least one add, we added operands to the end of the list,
663 // and they are not necessarily sorted. Recurse to resort and resimplify
664 // any operands we just aquired.
665 if (DeletedAdd)
666 return get(Ops);
667 }
668
669 // Skip over the add expression until we get to a multiply.
670 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
671 ++Idx;
672
673 // If we are adding something to a multiply expression, make sure the
674 // something is not already an operand of the multiply. If so, merge it into
675 // the multiply.
676 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
677 SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
678 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
679 SCEV *MulOpSCEV = Mul->getOperand(MulOp);
680 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
Chris Lattner6a1a78a2004-12-04 20:54:32 +0000681 if (MulOpSCEV == Ops[AddOp] && !isa<SCEVConstant>(MulOpSCEV)) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000682 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
683 SCEVHandle InnerMul = Mul->getOperand(MulOp == 0);
684 if (Mul->getNumOperands() != 2) {
685 // If the multiply has more than two operands, we must get the
686 // Y*Z term.
687 std::vector<SCEVHandle> MulOps(Mul->op_begin(), Mul->op_end());
688 MulOps.erase(MulOps.begin()+MulOp);
689 InnerMul = SCEVMulExpr::get(MulOps);
690 }
Chris Lattnerb06432c2004-04-23 21:29:03 +0000691 SCEVHandle One = SCEVUnknown::getIntegerSCEV(1, Ty);
Chris Lattner53e677a2004-04-02 20:23:17 +0000692 SCEVHandle AddOne = SCEVAddExpr::get(InnerMul, One);
693 SCEVHandle OuterMul = SCEVMulExpr::get(AddOne, Ops[AddOp]);
694 if (Ops.size() == 2) return OuterMul;
695 if (AddOp < Idx) {
696 Ops.erase(Ops.begin()+AddOp);
697 Ops.erase(Ops.begin()+Idx-1);
698 } else {
699 Ops.erase(Ops.begin()+Idx);
700 Ops.erase(Ops.begin()+AddOp-1);
701 }
702 Ops.push_back(OuterMul);
703 return SCEVAddExpr::get(Ops);
704 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000705
Chris Lattner53e677a2004-04-02 20:23:17 +0000706 // Check this multiply against other multiplies being added together.
707 for (unsigned OtherMulIdx = Idx+1;
708 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
709 ++OtherMulIdx) {
710 SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
711 // If MulOp occurs in OtherMul, we can fold the two multiplies
712 // together.
713 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
714 OMulOp != e; ++OMulOp)
715 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
716 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
717 SCEVHandle InnerMul1 = Mul->getOperand(MulOp == 0);
718 if (Mul->getNumOperands() != 2) {
719 std::vector<SCEVHandle> MulOps(Mul->op_begin(), Mul->op_end());
720 MulOps.erase(MulOps.begin()+MulOp);
721 InnerMul1 = SCEVMulExpr::get(MulOps);
722 }
723 SCEVHandle InnerMul2 = OtherMul->getOperand(OMulOp == 0);
724 if (OtherMul->getNumOperands() != 2) {
725 std::vector<SCEVHandle> MulOps(OtherMul->op_begin(),
726 OtherMul->op_end());
727 MulOps.erase(MulOps.begin()+OMulOp);
728 InnerMul2 = SCEVMulExpr::get(MulOps);
729 }
730 SCEVHandle InnerMulSum = SCEVAddExpr::get(InnerMul1,InnerMul2);
731 SCEVHandle OuterMul = SCEVMulExpr::get(MulOpSCEV, InnerMulSum);
732 if (Ops.size() == 2) return OuterMul;
733 Ops.erase(Ops.begin()+Idx);
734 Ops.erase(Ops.begin()+OtherMulIdx-1);
735 Ops.push_back(OuterMul);
736 return SCEVAddExpr::get(Ops);
737 }
738 }
739 }
740 }
741
742 // If there are any add recurrences in the operands list, see if any other
743 // added values are loop invariant. If so, we can fold them into the
744 // recurrence.
745 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
746 ++Idx;
747
748 // Scan over all recurrences, trying to fold loop invariants into them.
749 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
750 // Scan all of the other operands to this add and add them to the vector if
751 // they are loop invariant w.r.t. the recurrence.
752 std::vector<SCEVHandle> LIOps;
753 SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
754 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
755 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
756 LIOps.push_back(Ops[i]);
757 Ops.erase(Ops.begin()+i);
758 --i; --e;
759 }
760
761 // If we found some loop invariants, fold them into the recurrence.
762 if (!LIOps.empty()) {
763 // NLI + LI + { Start,+,Step} --> NLI + { LI+Start,+,Step }
764 LIOps.push_back(AddRec->getStart());
765
766 std::vector<SCEVHandle> AddRecOps(AddRec->op_begin(), AddRec->op_end());
767 AddRecOps[0] = SCEVAddExpr::get(LIOps);
768
769 SCEVHandle NewRec = SCEVAddRecExpr::get(AddRecOps, AddRec->getLoop());
770 // If all of the other operands were loop invariant, we are done.
771 if (Ops.size() == 1) return NewRec;
772
773 // Otherwise, add the folded AddRec by the non-liv parts.
774 for (unsigned i = 0;; ++i)
775 if (Ops[i] == AddRec) {
776 Ops[i] = NewRec;
777 break;
778 }
779 return SCEVAddExpr::get(Ops);
780 }
781
782 // Okay, if there weren't any loop invariants to be folded, check to see if
783 // there are multiple AddRec's with the same loop induction variable being
784 // added together. If so, we can fold them.
785 for (unsigned OtherIdx = Idx+1;
786 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
787 if (OtherIdx != Idx) {
788 SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
789 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
790 // Other + {A,+,B} + {C,+,D} --> Other + {A+C,+,B+D}
791 std::vector<SCEVHandle> NewOps(AddRec->op_begin(), AddRec->op_end());
792 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); i != e; ++i) {
793 if (i >= NewOps.size()) {
794 NewOps.insert(NewOps.end(), OtherAddRec->op_begin()+i,
795 OtherAddRec->op_end());
796 break;
797 }
798 NewOps[i] = SCEVAddExpr::get(NewOps[i], OtherAddRec->getOperand(i));
799 }
800 SCEVHandle NewAddRec = SCEVAddRecExpr::get(NewOps, AddRec->getLoop());
801
802 if (Ops.size() == 2) return NewAddRec;
803
804 Ops.erase(Ops.begin()+Idx);
805 Ops.erase(Ops.begin()+OtherIdx-1);
806 Ops.push_back(NewAddRec);
807 return SCEVAddExpr::get(Ops);
808 }
809 }
810
811 // Otherwise couldn't fold anything into this recurrence. Move onto the
812 // next one.
813 }
814
815 // Okay, it looks like we really DO need an add expr. Check to see if we
816 // already have one, otherwise create a new one.
817 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
Chris Lattnerb3364092006-10-04 21:49:37 +0000818 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scAddExpr,
819 SCEVOps)];
Chris Lattner53e677a2004-04-02 20:23:17 +0000820 if (Result == 0) Result = new SCEVAddExpr(Ops);
821 return Result;
822}
823
824
825SCEVHandle SCEVMulExpr::get(std::vector<SCEVHandle> &Ops) {
826 assert(!Ops.empty() && "Cannot get empty mul!");
827
828 // Sort by complexity, this groups all similar expression types together.
Chris Lattner8d741b82004-06-20 06:23:15 +0000829 GroupByComplexity(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +0000830
831 // If there are any constants, fold them together.
832 unsigned Idx = 0;
833 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
834
835 // C1*(C2+V) -> C1*C2 + C1*V
836 if (Ops.size() == 2)
837 if (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
838 if (Add->getNumOperands() == 2 &&
839 isa<SCEVConstant>(Add->getOperand(0)))
840 return SCEVAddExpr::get(SCEVMulExpr::get(LHSC, Add->getOperand(0)),
841 SCEVMulExpr::get(LHSC, Add->getOperand(1)));
842
843
844 ++Idx;
845 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
846 // We found two constants, fold them together!
847 Constant *Fold = ConstantExpr::getMul(LHSC->getValue(), RHSC->getValue());
848 if (ConstantInt *CI = dyn_cast<ConstantInt>(Fold)) {
849 Ops[0] = SCEVConstant::get(CI);
850 Ops.erase(Ops.begin()+1); // Erase the folded element
851 if (Ops.size() == 1) return Ops[0];
Chris Lattner7ffc07d2005-02-26 18:50:19 +0000852 LHSC = cast<SCEVConstant>(Ops[0]);
Chris Lattner53e677a2004-04-02 20:23:17 +0000853 } else {
854 // If we couldn't fold the expression, move to the next constant. Note
855 // that this is impossible to happen in practice because we always
856 // constant fold constant ints to constant ints.
857 ++Idx;
858 }
859 }
860
861 // If we are left with a constant one being multiplied, strip it off.
862 if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) {
863 Ops.erase(Ops.begin());
864 --Idx;
865 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isNullValue()) {
866 // If we have a multiply of zero, it will always be zero.
867 return Ops[0];
868 }
869 }
870
871 // Skip over the add expression until we get to a multiply.
872 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
873 ++Idx;
874
875 if (Ops.size() == 1)
876 return Ops[0];
Misha Brukman2b37d7c2005-04-21 21:13:18 +0000877
Chris Lattner53e677a2004-04-02 20:23:17 +0000878 // If there are mul operands inline them all into this expression.
879 if (Idx < Ops.size()) {
880 bool DeletedMul = false;
881 while (SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
882 // If we have an mul, expand the mul operands onto the end of the operands
883 // list.
884 Ops.insert(Ops.end(), Mul->op_begin(), Mul->op_end());
885 Ops.erase(Ops.begin()+Idx);
886 DeletedMul = true;
887 }
888
889 // If we deleted at least one mul, we added operands to the end of the list,
890 // and they are not necessarily sorted. Recurse to resort and resimplify
891 // any operands we just aquired.
892 if (DeletedMul)
893 return get(Ops);
894 }
895
896 // If there are any add recurrences in the operands list, see if any other
897 // added values are loop invariant. If so, we can fold them into the
898 // recurrence.
899 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
900 ++Idx;
901
902 // Scan over all recurrences, trying to fold loop invariants into them.
903 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
904 // Scan all of the other operands to this mul and add them to the vector if
905 // they are loop invariant w.r.t. the recurrence.
906 std::vector<SCEVHandle> LIOps;
907 SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
908 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
909 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
910 LIOps.push_back(Ops[i]);
911 Ops.erase(Ops.begin()+i);
912 --i; --e;
913 }
914
915 // If we found some loop invariants, fold them into the recurrence.
916 if (!LIOps.empty()) {
917 // NLI * LI * { Start,+,Step} --> NLI * { LI*Start,+,LI*Step }
918 std::vector<SCEVHandle> NewOps;
919 NewOps.reserve(AddRec->getNumOperands());
920 if (LIOps.size() == 1) {
921 SCEV *Scale = LIOps[0];
922 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
923 NewOps.push_back(SCEVMulExpr::get(Scale, AddRec->getOperand(i)));
924 } else {
925 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
926 std::vector<SCEVHandle> MulOps(LIOps);
927 MulOps.push_back(AddRec->getOperand(i));
928 NewOps.push_back(SCEVMulExpr::get(MulOps));
929 }
930 }
931
932 SCEVHandle NewRec = SCEVAddRecExpr::get(NewOps, AddRec->getLoop());
933
934 // If all of the other operands were loop invariant, we are done.
935 if (Ops.size() == 1) return NewRec;
936
937 // Otherwise, multiply the folded AddRec by the non-liv parts.
938 for (unsigned i = 0;; ++i)
939 if (Ops[i] == AddRec) {
940 Ops[i] = NewRec;
941 break;
942 }
943 return SCEVMulExpr::get(Ops);
944 }
945
946 // Okay, if there weren't any loop invariants to be folded, check to see if
947 // there are multiple AddRec's with the same loop induction variable being
948 // multiplied together. If so, we can fold them.
949 for (unsigned OtherIdx = Idx+1;
950 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
951 if (OtherIdx != Idx) {
952 SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
953 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
954 // F * G --> {A,+,B} * {C,+,D} --> {A*C,+,F*D + G*B + B*D}
955 SCEVAddRecExpr *F = AddRec, *G = OtherAddRec;
956 SCEVHandle NewStart = SCEVMulExpr::get(F->getStart(),
957 G->getStart());
958 SCEVHandle B = F->getStepRecurrence();
959 SCEVHandle D = G->getStepRecurrence();
960 SCEVHandle NewStep = SCEVAddExpr::get(SCEVMulExpr::get(F, D),
961 SCEVMulExpr::get(G, B),
962 SCEVMulExpr::get(B, D));
963 SCEVHandle NewAddRec = SCEVAddRecExpr::get(NewStart, NewStep,
964 F->getLoop());
965 if (Ops.size() == 2) return NewAddRec;
966
967 Ops.erase(Ops.begin()+Idx);
968 Ops.erase(Ops.begin()+OtherIdx-1);
969 Ops.push_back(NewAddRec);
970 return SCEVMulExpr::get(Ops);
971 }
972 }
973
974 // Otherwise couldn't fold anything into this recurrence. Move onto the
975 // next one.
976 }
977
978 // Okay, it looks like we really DO need an mul expr. Check to see if we
979 // already have one, otherwise create a new one.
980 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
Chris Lattnerb3364092006-10-04 21:49:37 +0000981 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scMulExpr,
982 SCEVOps)];
Chris Lattner6a1a78a2004-12-04 20:54:32 +0000983 if (Result == 0)
984 Result = new SCEVMulExpr(Ops);
Chris Lattner53e677a2004-04-02 20:23:17 +0000985 return Result;
986}
987
Chris Lattner60a05cc2006-04-01 04:48:52 +0000988SCEVHandle SCEVSDivExpr::get(const SCEVHandle &LHS, const SCEVHandle &RHS) {
Chris Lattner53e677a2004-04-02 20:23:17 +0000989 if (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
990 if (RHSC->getValue()->equalsInt(1))
Reid Spencer1628cec2006-10-26 06:15:43 +0000991 return LHS; // X sdiv 1 --> x
Chris Lattner53e677a2004-04-02 20:23:17 +0000992 if (RHSC->getValue()->isAllOnesValue())
Reid Spencer1628cec2006-10-26 06:15:43 +0000993 return SCEV::getNegativeSCEV(LHS); // X sdiv -1 --> -x
Chris Lattner53e677a2004-04-02 20:23:17 +0000994
995 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
996 Constant *LHSCV = LHSC->getValue();
997 Constant *RHSCV = RHSC->getValue();
Chris Lattner60a05cc2006-04-01 04:48:52 +0000998 if (LHSCV->getType()->isUnsigned())
Chris Lattner53e677a2004-04-02 20:23:17 +0000999 LHSCV = ConstantExpr::getCast(LHSCV,
Chris Lattner60a05cc2006-04-01 04:48:52 +00001000 LHSCV->getType()->getSignedVersion());
1001 if (RHSCV->getType()->isUnsigned())
Chris Lattner53e677a2004-04-02 20:23:17 +00001002 RHSCV = ConstantExpr::getCast(RHSCV, LHSCV->getType());
Reid Spencer1628cec2006-10-26 06:15:43 +00001003 return SCEVUnknown::get(ConstantExpr::getSDiv(LHSCV, RHSCV));
Chris Lattner53e677a2004-04-02 20:23:17 +00001004 }
1005 }
1006
1007 // FIXME: implement folding of (X*4)/4 when we know X*4 doesn't overflow.
1008
Chris Lattnerb3364092006-10-04 21:49:37 +00001009 SCEVSDivExpr *&Result = (*SCEVSDivs)[std::make_pair(LHS, RHS)];
Chris Lattner60a05cc2006-04-01 04:48:52 +00001010 if (Result == 0) Result = new SCEVSDivExpr(LHS, RHS);
Chris Lattner53e677a2004-04-02 20:23:17 +00001011 return Result;
1012}
1013
1014
1015/// SCEVAddRecExpr::get - Get a add recurrence expression for the
1016/// specified loop. Simplify the expression as much as possible.
1017SCEVHandle SCEVAddRecExpr::get(const SCEVHandle &Start,
1018 const SCEVHandle &Step, const Loop *L) {
1019 std::vector<SCEVHandle> Operands;
1020 Operands.push_back(Start);
1021 if (SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
1022 if (StepChrec->getLoop() == L) {
1023 Operands.insert(Operands.end(), StepChrec->op_begin(),
1024 StepChrec->op_end());
1025 return get(Operands, L);
1026 }
1027
1028 Operands.push_back(Step);
1029 return get(Operands, L);
1030}
1031
1032/// SCEVAddRecExpr::get - Get a add recurrence expression for the
1033/// specified loop. Simplify the expression as much as possible.
1034SCEVHandle SCEVAddRecExpr::get(std::vector<SCEVHandle> &Operands,
1035 const Loop *L) {
1036 if (Operands.size() == 1) return Operands[0];
1037
1038 if (SCEVConstant *StepC = dyn_cast<SCEVConstant>(Operands.back()))
1039 if (StepC->getValue()->isNullValue()) {
1040 Operands.pop_back();
1041 return get(Operands, L); // { X,+,0 } --> X
1042 }
1043
1044 SCEVAddRecExpr *&Result =
Chris Lattnerb3364092006-10-04 21:49:37 +00001045 (*SCEVAddRecExprs)[std::make_pair(L, std::vector<SCEV*>(Operands.begin(),
1046 Operands.end()))];
Chris Lattner53e677a2004-04-02 20:23:17 +00001047 if (Result == 0) Result = new SCEVAddRecExpr(Operands, L);
1048 return Result;
1049}
1050
Chris Lattner0a7f98c2004-04-15 15:07:24 +00001051SCEVHandle SCEVUnknown::get(Value *V) {
1052 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
1053 return SCEVConstant::get(CI);
Chris Lattnerb3364092006-10-04 21:49:37 +00001054 SCEVUnknown *&Result = (*SCEVUnknowns)[V];
Chris Lattner0a7f98c2004-04-15 15:07:24 +00001055 if (Result == 0) Result = new SCEVUnknown(V);
1056 return Result;
1057}
1058
Chris Lattner53e677a2004-04-02 20:23:17 +00001059
1060//===----------------------------------------------------------------------===//
Chris Lattner53e677a2004-04-02 20:23:17 +00001061// ScalarEvolutionsImpl Definition and Implementation
1062//===----------------------------------------------------------------------===//
1063//
1064/// ScalarEvolutionsImpl - This class implements the main driver for the scalar
1065/// evolution code.
1066///
1067namespace {
Chris Lattner95255282006-06-28 23:17:24 +00001068 struct VISIBILITY_HIDDEN ScalarEvolutionsImpl {
Chris Lattner53e677a2004-04-02 20:23:17 +00001069 /// F - The function we are analyzing.
1070 ///
1071 Function &F;
1072
1073 /// LI - The loop information for the function we are currently analyzing.
1074 ///
1075 LoopInfo &LI;
1076
1077 /// UnknownValue - This SCEV is used to represent unknown trip counts and
1078 /// things.
1079 SCEVHandle UnknownValue;
1080
1081 /// Scalars - This is a cache of the scalars we have analyzed so far.
1082 ///
1083 std::map<Value*, SCEVHandle> Scalars;
1084
1085 /// IterationCounts - Cache the iteration count of the loops for this
1086 /// function as they are computed.
1087 std::map<const Loop*, SCEVHandle> IterationCounts;
1088
Chris Lattner3221ad02004-04-17 22:58:41 +00001089 /// ConstantEvolutionLoopExitValue - This map contains entries for all of
1090 /// the PHI instructions that we attempt to compute constant evolutions for.
1091 /// This allows us to avoid potentially expensive recomputation of these
1092 /// properties. An instruction maps to null if we are unable to compute its
1093 /// exit value.
1094 std::map<PHINode*, Constant*> ConstantEvolutionLoopExitValue;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001095
Chris Lattner53e677a2004-04-02 20:23:17 +00001096 public:
1097 ScalarEvolutionsImpl(Function &f, LoopInfo &li)
1098 : F(f), LI(li), UnknownValue(new SCEVCouldNotCompute()) {}
1099
1100 /// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
1101 /// expression and create a new one.
1102 SCEVHandle getSCEV(Value *V);
1103
Chris Lattnera0740fb2005-08-09 23:36:33 +00001104 /// hasSCEV - Return true if the SCEV for this value has already been
1105 /// computed.
1106 bool hasSCEV(Value *V) const {
1107 return Scalars.count(V);
1108 }
1109
1110 /// setSCEV - Insert the specified SCEV into the map of current SCEVs for
1111 /// the specified value.
1112 void setSCEV(Value *V, const SCEVHandle &H) {
1113 bool isNew = Scalars.insert(std::make_pair(V, H)).second;
1114 assert(isNew && "This entry already existed!");
1115 }
1116
1117
Chris Lattner53e677a2004-04-02 20:23:17 +00001118 /// getSCEVAtScope - Compute the value of the specified expression within
1119 /// the indicated loop (which may be null to indicate in no loop). If the
1120 /// expression cannot be evaluated, return UnknownValue itself.
1121 SCEVHandle getSCEVAtScope(SCEV *V, const Loop *L);
1122
1123
1124 /// hasLoopInvariantIterationCount - Return true if the specified loop has
1125 /// an analyzable loop-invariant iteration count.
1126 bool hasLoopInvariantIterationCount(const Loop *L);
1127
1128 /// getIterationCount - If the specified loop has a predictable iteration
1129 /// count, return it. Note that it is not valid to call this method on a
1130 /// loop without a loop-invariant iteration count.
1131 SCEVHandle getIterationCount(const Loop *L);
1132
1133 /// deleteInstructionFromRecords - This method should be called by the
1134 /// client before it removes an instruction from the program, to make sure
1135 /// that no dangling references are left around.
1136 void deleteInstructionFromRecords(Instruction *I);
1137
1138 private:
1139 /// createSCEV - We know that there is no SCEV for the specified value.
1140 /// Analyze the expression.
1141 SCEVHandle createSCEV(Value *V);
Chris Lattner53e677a2004-04-02 20:23:17 +00001142
1143 /// createNodeForPHI - Provide the special handling we need to analyze PHI
1144 /// SCEVs.
1145 SCEVHandle createNodeForPHI(PHINode *PN);
Chris Lattner4dc534c2005-02-13 04:37:18 +00001146
1147 /// ReplaceSymbolicValueWithConcrete - This looks up the computed SCEV value
1148 /// for the specified instruction and replaces any references to the
1149 /// symbolic value SymName with the specified value. This is used during
1150 /// PHI resolution.
1151 void ReplaceSymbolicValueWithConcrete(Instruction *I,
1152 const SCEVHandle &SymName,
1153 const SCEVHandle &NewVal);
Chris Lattner53e677a2004-04-02 20:23:17 +00001154
1155 /// ComputeIterationCount - Compute the number of times the specified loop
1156 /// will iterate.
1157 SCEVHandle ComputeIterationCount(const Loop *L);
1158
Chris Lattner673e02b2004-10-12 01:49:27 +00001159 /// ComputeLoadConstantCompareIterationCount - Given an exit condition of
1160 /// 'setcc load X, cst', try to se if we can compute the trip count.
1161 SCEVHandle ComputeLoadConstantCompareIterationCount(LoadInst *LI,
1162 Constant *RHS,
1163 const Loop *L,
1164 unsigned SetCCOpcode);
1165
Chris Lattner7980fb92004-04-17 18:36:24 +00001166 /// ComputeIterationCountExhaustively - If the trip is known to execute a
1167 /// constant number of times (the condition evolves only from constants),
1168 /// try to evaluate a few iterations of the loop until we get the exit
1169 /// condition gets a value of ExitWhen (true or false). If we cannot
1170 /// evaluate the trip count of the loop, return UnknownValue.
1171 SCEVHandle ComputeIterationCountExhaustively(const Loop *L, Value *Cond,
1172 bool ExitWhen);
1173
Chris Lattner53e677a2004-04-02 20:23:17 +00001174 /// HowFarToZero - Return the number of times a backedge comparing the
1175 /// specified value to zero will execute. If not computable, return
Chris Lattnerdb25de42005-08-15 23:33:51 +00001176 /// UnknownValue.
Chris Lattner53e677a2004-04-02 20:23:17 +00001177 SCEVHandle HowFarToZero(SCEV *V, const Loop *L);
1178
1179 /// HowFarToNonZero - Return the number of times a backedge checking the
1180 /// specified value for nonzero will execute. If not computable, return
Chris Lattnerdb25de42005-08-15 23:33:51 +00001181 /// UnknownValue.
Chris Lattner53e677a2004-04-02 20:23:17 +00001182 SCEVHandle HowFarToNonZero(SCEV *V, const Loop *L);
Chris Lattner3221ad02004-04-17 22:58:41 +00001183
Chris Lattnerdb25de42005-08-15 23:33:51 +00001184 /// HowManyLessThans - Return the number of times a backedge containing the
1185 /// specified less-than comparison will execute. If not computable, return
1186 /// UnknownValue.
1187 SCEVHandle HowManyLessThans(SCEV *LHS, SCEV *RHS, const Loop *L);
1188
Chris Lattner3221ad02004-04-17 22:58:41 +00001189 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
1190 /// in the header of its containing loop, we know the loop executes a
1191 /// constant number of times, and the PHI node is just a recurrence
1192 /// involving constants, fold it.
1193 Constant *getConstantEvolutionLoopExitValue(PHINode *PN, uint64_t Its,
1194 const Loop *L);
Chris Lattner53e677a2004-04-02 20:23:17 +00001195 };
1196}
1197
1198//===----------------------------------------------------------------------===//
1199// Basic SCEV Analysis and PHI Idiom Recognition Code
1200//
1201
1202/// deleteInstructionFromRecords - This method should be called by the
1203/// client before it removes an instruction from the program, to make sure
1204/// that no dangling references are left around.
1205void ScalarEvolutionsImpl::deleteInstructionFromRecords(Instruction *I) {
1206 Scalars.erase(I);
Chris Lattner3221ad02004-04-17 22:58:41 +00001207 if (PHINode *PN = dyn_cast<PHINode>(I))
1208 ConstantEvolutionLoopExitValue.erase(PN);
Chris Lattner53e677a2004-04-02 20:23:17 +00001209}
1210
1211
1212/// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
1213/// expression and create a new one.
1214SCEVHandle ScalarEvolutionsImpl::getSCEV(Value *V) {
1215 assert(V->getType() != Type::VoidTy && "Can't analyze void expressions!");
1216
1217 std::map<Value*, SCEVHandle>::iterator I = Scalars.find(V);
1218 if (I != Scalars.end()) return I->second;
1219 SCEVHandle S = createSCEV(V);
1220 Scalars.insert(std::make_pair(V, S));
1221 return S;
1222}
1223
Chris Lattner4dc534c2005-02-13 04:37:18 +00001224/// ReplaceSymbolicValueWithConcrete - This looks up the computed SCEV value for
1225/// the specified instruction and replaces any references to the symbolic value
1226/// SymName with the specified value. This is used during PHI resolution.
1227void ScalarEvolutionsImpl::
1228ReplaceSymbolicValueWithConcrete(Instruction *I, const SCEVHandle &SymName,
1229 const SCEVHandle &NewVal) {
Chris Lattner53e677a2004-04-02 20:23:17 +00001230 std::map<Value*, SCEVHandle>::iterator SI = Scalars.find(I);
Chris Lattner4dc534c2005-02-13 04:37:18 +00001231 if (SI == Scalars.end()) return;
Chris Lattner53e677a2004-04-02 20:23:17 +00001232
Chris Lattner4dc534c2005-02-13 04:37:18 +00001233 SCEVHandle NV =
1234 SI->second->replaceSymbolicValuesWithConcrete(SymName, NewVal);
1235 if (NV == SI->second) return; // No change.
1236
1237 SI->second = NV; // Update the scalars map!
1238
1239 // Any instruction values that use this instruction might also need to be
1240 // updated!
1241 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1242 UI != E; ++UI)
1243 ReplaceSymbolicValueWithConcrete(cast<Instruction>(*UI), SymName, NewVal);
1244}
Chris Lattner53e677a2004-04-02 20:23:17 +00001245
1246/// createNodeForPHI - PHI nodes have two cases. Either the PHI node exists in
1247/// a loop header, making it a potential recurrence, or it doesn't.
1248///
1249SCEVHandle ScalarEvolutionsImpl::createNodeForPHI(PHINode *PN) {
1250 if (PN->getNumIncomingValues() == 2) // The loops have been canonicalized.
1251 if (const Loop *L = LI.getLoopFor(PN->getParent()))
1252 if (L->getHeader() == PN->getParent()) {
1253 // If it lives in the loop header, it has two incoming values, one
1254 // from outside the loop, and one from inside.
1255 unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0));
1256 unsigned BackEdge = IncomingEdge^1;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001257
Chris Lattner53e677a2004-04-02 20:23:17 +00001258 // While we are analyzing this PHI node, handle its value symbolically.
1259 SCEVHandle SymbolicName = SCEVUnknown::get(PN);
1260 assert(Scalars.find(PN) == Scalars.end() &&
1261 "PHI node already processed?");
1262 Scalars.insert(std::make_pair(PN, SymbolicName));
1263
1264 // Using this symbolic name for the PHI, analyze the value coming around
1265 // the back-edge.
1266 SCEVHandle BEValue = getSCEV(PN->getIncomingValue(BackEdge));
1267
1268 // NOTE: If BEValue is loop invariant, we know that the PHI node just
1269 // has a special value for the first iteration of the loop.
1270
1271 // If the value coming around the backedge is an add with the symbolic
1272 // value we just inserted, then we found a simple induction variable!
1273 if (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
1274 // If there is a single occurrence of the symbolic value, replace it
1275 // with a recurrence.
1276 unsigned FoundIndex = Add->getNumOperands();
1277 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
1278 if (Add->getOperand(i) == SymbolicName)
1279 if (FoundIndex == e) {
1280 FoundIndex = i;
1281 break;
1282 }
1283
1284 if (FoundIndex != Add->getNumOperands()) {
1285 // Create an add with everything but the specified operand.
1286 std::vector<SCEVHandle> Ops;
1287 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
1288 if (i != FoundIndex)
1289 Ops.push_back(Add->getOperand(i));
1290 SCEVHandle Accum = SCEVAddExpr::get(Ops);
1291
1292 // This is not a valid addrec if the step amount is varying each
1293 // loop iteration, but is not itself an addrec in this loop.
1294 if (Accum->isLoopInvariant(L) ||
1295 (isa<SCEVAddRecExpr>(Accum) &&
1296 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
1297 SCEVHandle StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
1298 SCEVHandle PHISCEV = SCEVAddRecExpr::get(StartVal, Accum, L);
1299
1300 // Okay, for the entire analysis of this edge we assumed the PHI
1301 // to be symbolic. We now need to go back and update all of the
1302 // entries for the scalars that use the PHI (except for the PHI
1303 // itself) to use the new analyzed value instead of the "symbolic"
1304 // value.
Chris Lattner4dc534c2005-02-13 04:37:18 +00001305 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
Chris Lattner53e677a2004-04-02 20:23:17 +00001306 return PHISCEV;
1307 }
1308 }
Chris Lattner97156e72006-04-26 18:34:07 +00001309 } else if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(BEValue)) {
1310 // Otherwise, this could be a loop like this:
1311 // i = 0; for (j = 1; ..; ++j) { .... i = j; }
1312 // In this case, j = {1,+,1} and BEValue is j.
1313 // Because the other in-value of i (0) fits the evolution of BEValue
1314 // i really is an addrec evolution.
1315 if (AddRec->getLoop() == L && AddRec->isAffine()) {
1316 SCEVHandle StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
1317
1318 // If StartVal = j.start - j.stride, we can use StartVal as the
1319 // initial step of the addrec evolution.
1320 if (StartVal == SCEV::getMinusSCEV(AddRec->getOperand(0),
1321 AddRec->getOperand(1))) {
1322 SCEVHandle PHISCEV =
1323 SCEVAddRecExpr::get(StartVal, AddRec->getOperand(1), L);
1324
1325 // Okay, for the entire analysis of this edge we assumed the PHI
1326 // to be symbolic. We now need to go back and update all of the
1327 // entries for the scalars that use the PHI (except for the PHI
1328 // itself) to use the new analyzed value instead of the "symbolic"
1329 // value.
1330 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
1331 return PHISCEV;
1332 }
1333 }
Chris Lattner53e677a2004-04-02 20:23:17 +00001334 }
1335
1336 return SymbolicName;
1337 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001338
Chris Lattner53e677a2004-04-02 20:23:17 +00001339 // If it's not a loop phi, we can't handle it yet.
1340 return SCEVUnknown::get(PN);
1341}
1342
Chris Lattner53e677a2004-04-02 20:23:17 +00001343
1344/// createSCEV - We know that there is no SCEV for the specified value.
1345/// Analyze the expression.
1346///
1347SCEVHandle ScalarEvolutionsImpl::createSCEV(Value *V) {
1348 if (Instruction *I = dyn_cast<Instruction>(V)) {
1349 switch (I->getOpcode()) {
1350 case Instruction::Add:
1351 return SCEVAddExpr::get(getSCEV(I->getOperand(0)),
1352 getSCEV(I->getOperand(1)));
1353 case Instruction::Mul:
1354 return SCEVMulExpr::get(getSCEV(I->getOperand(0)),
1355 getSCEV(I->getOperand(1)));
Reid Spencer1628cec2006-10-26 06:15:43 +00001356 case Instruction::SDiv:
1357 return SCEVSDivExpr::get(getSCEV(I->getOperand(0)),
1358 getSCEV(I->getOperand(1)));
Chris Lattner53e677a2004-04-02 20:23:17 +00001359 break;
1360
1361 case Instruction::Sub:
Chris Lattnerbac5b462005-03-09 05:34:41 +00001362 return SCEV::getMinusSCEV(getSCEV(I->getOperand(0)),
1363 getSCEV(I->getOperand(1)));
Chris Lattner53e677a2004-04-02 20:23:17 +00001364
1365 case Instruction::Shl:
1366 // Turn shift left of a constant amount into a multiply.
1367 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1368 Constant *X = ConstantInt::get(V->getType(), 1);
1369 X = ConstantExpr::getShl(X, SA);
1370 return SCEVMulExpr::get(getSCEV(I->getOperand(0)), getSCEV(X));
1371 }
1372 break;
1373
Reid Spencer3da59db2006-11-27 01:05:10 +00001374 case Instruction::Trunc:
1375 if (I->getType()->isInteger() && I->getOperand(0)->getType()->isInteger())
1376 return SCEVTruncateExpr::get(getSCEV(I->getOperand(0)),
1377 I->getType()->getUnsignedVersion());
1378 break;
1379
1380 case Instruction::ZExt:
1381 if (I->getType()->isInteger() && I->getOperand(0)->getType()->isInteger())
1382 return SCEVZeroExtendExpr::get(getSCEV(I->getOperand(0)),
1383 I->getType()->getUnsignedVersion());
1384 break;
1385
1386 case Instruction::BitCast:
1387 // BitCasts are no-op casts so we just eliminate the cast.
1388 return getSCEV(I->getOperand(0));
Chris Lattner53e677a2004-04-02 20:23:17 +00001389
1390 case Instruction::PHI:
1391 return createNodeForPHI(cast<PHINode>(I));
1392
1393 default: // We cannot analyze this expression.
1394 break;
1395 }
1396 }
1397
1398 return SCEVUnknown::get(V);
1399}
1400
1401
1402
1403//===----------------------------------------------------------------------===//
1404// Iteration Count Computation Code
1405//
1406
1407/// getIterationCount - If the specified loop has a predictable iteration
1408/// count, return it. Note that it is not valid to call this method on a
1409/// loop without a loop-invariant iteration count.
1410SCEVHandle ScalarEvolutionsImpl::getIterationCount(const Loop *L) {
1411 std::map<const Loop*, SCEVHandle>::iterator I = IterationCounts.find(L);
1412 if (I == IterationCounts.end()) {
1413 SCEVHandle ItCount = ComputeIterationCount(L);
1414 I = IterationCounts.insert(std::make_pair(L, ItCount)).first;
1415 if (ItCount != UnknownValue) {
1416 assert(ItCount->isLoopInvariant(L) &&
1417 "Computed trip count isn't loop invariant for loop!");
1418 ++NumTripCountsComputed;
1419 } else if (isa<PHINode>(L->getHeader()->begin())) {
1420 // Only count loops that have phi nodes as not being computable.
1421 ++NumTripCountsNotComputed;
1422 }
1423 }
1424 return I->second;
1425}
1426
1427/// ComputeIterationCount - Compute the number of times the specified loop
1428/// will iterate.
1429SCEVHandle ScalarEvolutionsImpl::ComputeIterationCount(const Loop *L) {
1430 // If the loop has a non-one exit block count, we can't analyze it.
Chris Lattnerf1ab4b42004-04-18 22:14:10 +00001431 std::vector<BasicBlock*> ExitBlocks;
1432 L->getExitBlocks(ExitBlocks);
1433 if (ExitBlocks.size() != 1) return UnknownValue;
Chris Lattner53e677a2004-04-02 20:23:17 +00001434
1435 // Okay, there is one exit block. Try to find the condition that causes the
1436 // loop to be exited.
Chris Lattnerf1ab4b42004-04-18 22:14:10 +00001437 BasicBlock *ExitBlock = ExitBlocks[0];
Chris Lattner53e677a2004-04-02 20:23:17 +00001438
1439 BasicBlock *ExitingBlock = 0;
1440 for (pred_iterator PI = pred_begin(ExitBlock), E = pred_end(ExitBlock);
1441 PI != E; ++PI)
1442 if (L->contains(*PI)) {
1443 if (ExitingBlock == 0)
1444 ExitingBlock = *PI;
1445 else
1446 return UnknownValue; // More than one block exiting!
1447 }
1448 assert(ExitingBlock && "No exits from loop, something is broken!");
1449
1450 // Okay, we've computed the exiting block. See what condition causes us to
1451 // exit.
1452 //
1453 // FIXME: we should be able to handle switch instructions (with a single exit)
1454 // FIXME: We should handle cast of int to bool as well
1455 BranchInst *ExitBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
1456 if (ExitBr == 0) return UnknownValue;
1457 assert(ExitBr->isConditional() && "If unconditional, it can't be in loop!");
1458 SetCondInst *ExitCond = dyn_cast<SetCondInst>(ExitBr->getCondition());
Chris Lattner7980fb92004-04-17 18:36:24 +00001459 if (ExitCond == 0) // Not a setcc
1460 return ComputeIterationCountExhaustively(L, ExitBr->getCondition(),
1461 ExitBr->getSuccessor(0) == ExitBlock);
Chris Lattner53e677a2004-04-02 20:23:17 +00001462
Chris Lattner673e02b2004-10-12 01:49:27 +00001463 // If the condition was exit on true, convert the condition to exit on false.
1464 Instruction::BinaryOps Cond;
1465 if (ExitBr->getSuccessor(1) == ExitBlock)
1466 Cond = ExitCond->getOpcode();
1467 else
1468 Cond = ExitCond->getInverseCondition();
1469
1470 // Handle common loops like: for (X = "string"; *X; ++X)
1471 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
1472 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
1473 SCEVHandle ItCnt =
1474 ComputeLoadConstantCompareIterationCount(LI, RHS, L, Cond);
1475 if (!isa<SCEVCouldNotCompute>(ItCnt)) return ItCnt;
1476 }
1477
Chris Lattner53e677a2004-04-02 20:23:17 +00001478 SCEVHandle LHS = getSCEV(ExitCond->getOperand(0));
1479 SCEVHandle RHS = getSCEV(ExitCond->getOperand(1));
1480
1481 // Try to evaluate any dependencies out of the loop.
1482 SCEVHandle Tmp = getSCEVAtScope(LHS, L);
1483 if (!isa<SCEVCouldNotCompute>(Tmp)) LHS = Tmp;
1484 Tmp = getSCEVAtScope(RHS, L);
1485 if (!isa<SCEVCouldNotCompute>(Tmp)) RHS = Tmp;
1486
Chris Lattner53e677a2004-04-02 20:23:17 +00001487 // At this point, we would like to compute how many iterations of the loop the
1488 // predicate will return true for these inputs.
1489 if (isa<SCEVConstant>(LHS) && !isa<SCEVConstant>(RHS)) {
1490 // If there is a constant, force it into the RHS.
1491 std::swap(LHS, RHS);
1492 Cond = SetCondInst::getSwappedCondition(Cond);
1493 }
1494
1495 // FIXME: think about handling pointer comparisons! i.e.:
1496 // while (P != P+100) ++P;
1497
1498 // If we have a comparison of a chrec against a constant, try to use value
1499 // ranges to answer this query.
1500 if (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
1501 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
1502 if (AddRec->getLoop() == L) {
1503 // Form the comparison range using the constant of the correct type so
1504 // that the ConstantRange class knows to do a signed or unsigned
1505 // comparison.
1506 ConstantInt *CompVal = RHSC->getValue();
1507 const Type *RealTy = ExitCond->getOperand(0)->getType();
1508 CompVal = dyn_cast<ConstantInt>(ConstantExpr::getCast(CompVal, RealTy));
1509 if (CompVal) {
1510 // Form the constant range.
1511 ConstantRange CompRange(Cond, CompVal);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001512
Chris Lattner53e677a2004-04-02 20:23:17 +00001513 // Now that we have it, if it's signed, convert it to an unsigned
1514 // range.
1515 if (CompRange.getLower()->getType()->isSigned()) {
1516 const Type *NewTy = RHSC->getValue()->getType();
1517 Constant *NewL = ConstantExpr::getCast(CompRange.getLower(), NewTy);
1518 Constant *NewU = ConstantExpr::getCast(CompRange.getUpper(), NewTy);
1519 CompRange = ConstantRange(NewL, NewU);
1520 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001521
Chris Lattner53e677a2004-04-02 20:23:17 +00001522 SCEVHandle Ret = AddRec->getNumIterationsInRange(CompRange);
1523 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
1524 }
1525 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001526
Chris Lattner53e677a2004-04-02 20:23:17 +00001527 switch (Cond) {
1528 case Instruction::SetNE: // while (X != Y)
1529 // Convert to: while (X-Y != 0)
Chris Lattner7980fb92004-04-17 18:36:24 +00001530 if (LHS->getType()->isInteger()) {
Chris Lattnerbac5b462005-03-09 05:34:41 +00001531 SCEVHandle TC = HowFarToZero(SCEV::getMinusSCEV(LHS, RHS), L);
Chris Lattner7980fb92004-04-17 18:36:24 +00001532 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
1533 }
Chris Lattner53e677a2004-04-02 20:23:17 +00001534 break;
1535 case Instruction::SetEQ:
1536 // Convert to: while (X-Y == 0) // while (X == Y)
Chris Lattner7980fb92004-04-17 18:36:24 +00001537 if (LHS->getType()->isInteger()) {
Chris Lattnerbac5b462005-03-09 05:34:41 +00001538 SCEVHandle TC = HowFarToNonZero(SCEV::getMinusSCEV(LHS, RHS), L);
Chris Lattner7980fb92004-04-17 18:36:24 +00001539 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
1540 }
Chris Lattner53e677a2004-04-02 20:23:17 +00001541 break;
Chris Lattnerdb25de42005-08-15 23:33:51 +00001542 case Instruction::SetLT:
1543 if (LHS->getType()->isInteger() &&
1544 ExitCond->getOperand(0)->getType()->isSigned()) {
1545 SCEVHandle TC = HowManyLessThans(LHS, RHS, L);
1546 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
1547 }
1548 break;
1549 case Instruction::SetGT:
1550 if (LHS->getType()->isInteger() &&
1551 ExitCond->getOperand(0)->getType()->isSigned()) {
1552 SCEVHandle TC = HowManyLessThans(RHS, LHS, L);
1553 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
1554 }
1555 break;
Chris Lattner53e677a2004-04-02 20:23:17 +00001556 default:
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00001557#if 0
Bill Wendling6f81b512006-11-28 22:46:12 +00001558 llvm_cerr << "ComputeIterationCount ";
Chris Lattner53e677a2004-04-02 20:23:17 +00001559 if (ExitCond->getOperand(0)->getType()->isUnsigned())
Bill Wendling6f81b512006-11-28 22:46:12 +00001560 llvm_cerr << "[unsigned] ";
1561 llvm_cerr << *LHS << " "
Chris Lattner53e677a2004-04-02 20:23:17 +00001562 << Instruction::getOpcodeName(Cond) << " " << *RHS << "\n";
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00001563#endif
Chris Lattnere34c0b42004-04-03 00:43:03 +00001564 break;
Chris Lattner53e677a2004-04-02 20:23:17 +00001565 }
Chris Lattner7980fb92004-04-17 18:36:24 +00001566
1567 return ComputeIterationCountExhaustively(L, ExitCond,
1568 ExitBr->getSuccessor(0) == ExitBlock);
1569}
1570
Chris Lattner673e02b2004-10-12 01:49:27 +00001571static ConstantInt *
1572EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, Constant *C) {
1573 SCEVHandle InVal = SCEVConstant::get(cast<ConstantInt>(C));
1574 SCEVHandle Val = AddRec->evaluateAtIteration(InVal);
1575 assert(isa<SCEVConstant>(Val) &&
1576 "Evaluation of SCEV at constant didn't fold correctly?");
1577 return cast<SCEVConstant>(Val)->getValue();
1578}
1579
1580/// GetAddressedElementFromGlobal - Given a global variable with an initializer
1581/// and a GEP expression (missing the pointer index) indexing into it, return
1582/// the addressed element of the initializer or null if the index expression is
1583/// invalid.
1584static Constant *
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001585GetAddressedElementFromGlobal(GlobalVariable *GV,
Chris Lattner673e02b2004-10-12 01:49:27 +00001586 const std::vector<ConstantInt*> &Indices) {
1587 Constant *Init = GV->getInitializer();
1588 for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
Reid Spencerb83eb642006-10-20 07:07:24 +00001589 uint64_t Idx = Indices[i]->getZExtValue();
Chris Lattner673e02b2004-10-12 01:49:27 +00001590 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
1591 assert(Idx < CS->getNumOperands() && "Bad struct index!");
1592 Init = cast<Constant>(CS->getOperand(Idx));
1593 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
1594 if (Idx >= CA->getNumOperands()) return 0; // Bogus program
1595 Init = cast<Constant>(CA->getOperand(Idx));
1596 } else if (isa<ConstantAggregateZero>(Init)) {
1597 if (const StructType *STy = dyn_cast<StructType>(Init->getType())) {
1598 assert(Idx < STy->getNumElements() && "Bad struct index!");
1599 Init = Constant::getNullValue(STy->getElementType(Idx));
1600 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Init->getType())) {
1601 if (Idx >= ATy->getNumElements()) return 0; // Bogus program
1602 Init = Constant::getNullValue(ATy->getElementType());
1603 } else {
1604 assert(0 && "Unknown constant aggregate type!");
1605 }
1606 return 0;
1607 } else {
1608 return 0; // Unknown initializer type
1609 }
1610 }
1611 return Init;
1612}
1613
1614/// ComputeLoadConstantCompareIterationCount - Given an exit condition of
1615/// 'setcc load X, cst', try to se if we can compute the trip count.
1616SCEVHandle ScalarEvolutionsImpl::
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001617ComputeLoadConstantCompareIterationCount(LoadInst *LI, Constant *RHS,
Chris Lattner673e02b2004-10-12 01:49:27 +00001618 const Loop *L, unsigned SetCCOpcode) {
1619 if (LI->isVolatile()) return UnknownValue;
1620
1621 // Check to see if the loaded pointer is a getelementptr of a global.
1622 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
1623 if (!GEP) return UnknownValue;
1624
1625 // Make sure that it is really a constant global we are gepping, with an
1626 // initializer, and make sure the first IDX is really 0.
1627 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
1628 if (!GV || !GV->isConstant() || !GV->hasInitializer() ||
1629 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
1630 !cast<Constant>(GEP->getOperand(1))->isNullValue())
1631 return UnknownValue;
1632
1633 // Okay, we allow one non-constant index into the GEP instruction.
1634 Value *VarIdx = 0;
1635 std::vector<ConstantInt*> Indexes;
1636 unsigned VarIdxNum = 0;
1637 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
1638 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
1639 Indexes.push_back(CI);
1640 } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
1641 if (VarIdx) return UnknownValue; // Multiple non-constant idx's.
1642 VarIdx = GEP->getOperand(i);
1643 VarIdxNum = i-2;
1644 Indexes.push_back(0);
1645 }
1646
1647 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
1648 // Check to see if X is a loop variant variable value now.
1649 SCEVHandle Idx = getSCEV(VarIdx);
1650 SCEVHandle Tmp = getSCEVAtScope(Idx, L);
1651 if (!isa<SCEVCouldNotCompute>(Tmp)) Idx = Tmp;
1652
1653 // We can only recognize very limited forms of loop index expressions, in
1654 // particular, only affine AddRec's like {C1,+,C2}.
1655 SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
1656 if (!IdxExpr || !IdxExpr->isAffine() || IdxExpr->isLoopInvariant(L) ||
1657 !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
1658 !isa<SCEVConstant>(IdxExpr->getOperand(1)))
1659 return UnknownValue;
1660
1661 unsigned MaxSteps = MaxBruteForceIterations;
1662 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
Reid Spencerb83eb642006-10-20 07:07:24 +00001663 ConstantInt *ItCst =
1664 ConstantInt::get(IdxExpr->getType()->getUnsignedVersion(), IterationNum);
Chris Lattner673e02b2004-10-12 01:49:27 +00001665 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst);
1666
1667 // Form the GEP offset.
1668 Indexes[VarIdxNum] = Val;
1669
1670 Constant *Result = GetAddressedElementFromGlobal(GV, Indexes);
1671 if (Result == 0) break; // Cannot compute!
1672
1673 // Evaluate the condition for this iteration.
1674 Result = ConstantExpr::get(SetCCOpcode, Result, RHS);
1675 if (!isa<ConstantBool>(Result)) break; // Couldn't decide for sure
Chris Lattner003cbf32006-09-28 23:36:21 +00001676 if (cast<ConstantBool>(Result)->getValue() == false) {
Chris Lattner673e02b2004-10-12 01:49:27 +00001677#if 0
Bill Wendling6f81b512006-11-28 22:46:12 +00001678 llvm_cerr << "\n***\n*** Computed loop count " << *ItCst
Chris Lattner673e02b2004-10-12 01:49:27 +00001679 << "\n*** From global " << *GV << "*** BB: " << *L->getHeader()
1680 << "***\n";
1681#endif
1682 ++NumArrayLenItCounts;
1683 return SCEVConstant::get(ItCst); // Found terminating iteration!
1684 }
1685 }
1686 return UnknownValue;
1687}
1688
1689
Chris Lattner3221ad02004-04-17 22:58:41 +00001690/// CanConstantFold - Return true if we can constant fold an instruction of the
1691/// specified type, assuming that all operands were constants.
1692static bool CanConstantFold(const Instruction *I) {
1693 if (isa<BinaryOperator>(I) || isa<ShiftInst>(I) ||
1694 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I))
1695 return true;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001696
Chris Lattner3221ad02004-04-17 22:58:41 +00001697 if (const CallInst *CI = dyn_cast<CallInst>(I))
1698 if (const Function *F = CI->getCalledFunction())
1699 return canConstantFoldCallTo((Function*)F); // FIXME: elim cast
1700 return false;
Chris Lattner7980fb92004-04-17 18:36:24 +00001701}
1702
Chris Lattner3221ad02004-04-17 22:58:41 +00001703/// ConstantFold - Constant fold an instruction of the specified type with the
1704/// specified constant operands. This function may modify the operands vector.
1705static Constant *ConstantFold(const Instruction *I,
1706 std::vector<Constant*> &Operands) {
Chris Lattner7980fb92004-04-17 18:36:24 +00001707 if (isa<BinaryOperator>(I) || isa<ShiftInst>(I))
1708 return ConstantExpr::get(I->getOpcode(), Operands[0], Operands[1]);
1709
Reid Spencer3da59db2006-11-27 01:05:10 +00001710 if (isa<CastInst>(I))
1711 return ConstantExpr::getCast(I->getOpcode(), Operands[0], I->getType());
1712
Chris Lattner7980fb92004-04-17 18:36:24 +00001713 switch (I->getOpcode()) {
Chris Lattner7980fb92004-04-17 18:36:24 +00001714 case Instruction::Select:
1715 return ConstantExpr::getSelect(Operands[0], Operands[1], Operands[2]);
1716 case Instruction::Call:
Reid Spencere8404342004-07-18 00:18:30 +00001717 if (Function *GV = dyn_cast<Function>(Operands[0])) {
Chris Lattner7980fb92004-04-17 18:36:24 +00001718 Operands.erase(Operands.begin());
Reid Spencere8404342004-07-18 00:18:30 +00001719 return ConstantFoldCall(cast<Function>(GV), Operands);
Chris Lattner7980fb92004-04-17 18:36:24 +00001720 }
Chris Lattner7980fb92004-04-17 18:36:24 +00001721 return 0;
1722 case Instruction::GetElementPtr:
1723 Constant *Base = Operands[0];
1724 Operands.erase(Operands.begin());
1725 return ConstantExpr::getGetElementPtr(Base, Operands);
1726 }
1727 return 0;
1728}
1729
1730
Chris Lattner3221ad02004-04-17 22:58:41 +00001731/// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
1732/// in the loop that V is derived from. We allow arbitrary operations along the
1733/// way, but the operands of an operation must either be constants or a value
1734/// derived from a constant PHI. If this expression does not fit with these
1735/// constraints, return null.
1736static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
1737 // If this is not an instruction, or if this is an instruction outside of the
1738 // loop, it can't be derived from a loop PHI.
1739 Instruction *I = dyn_cast<Instruction>(V);
1740 if (I == 0 || !L->contains(I->getParent())) return 0;
1741
1742 if (PHINode *PN = dyn_cast<PHINode>(I))
1743 if (L->getHeader() == I->getParent())
1744 return PN;
1745 else
1746 // We don't currently keep track of the control flow needed to evaluate
1747 // PHIs, so we cannot handle PHIs inside of loops.
1748 return 0;
1749
1750 // If we won't be able to constant fold this expression even if the operands
1751 // are constants, return early.
1752 if (!CanConstantFold(I)) return 0;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001753
Chris Lattner3221ad02004-04-17 22:58:41 +00001754 // Otherwise, we can evaluate this instruction if all of its operands are
1755 // constant or derived from a PHI node themselves.
1756 PHINode *PHI = 0;
1757 for (unsigned Op = 0, e = I->getNumOperands(); Op != e; ++Op)
1758 if (!(isa<Constant>(I->getOperand(Op)) ||
1759 isa<GlobalValue>(I->getOperand(Op)))) {
1760 PHINode *P = getConstantEvolvingPHI(I->getOperand(Op), L);
1761 if (P == 0) return 0; // Not evolving from PHI
1762 if (PHI == 0)
1763 PHI = P;
1764 else if (PHI != P)
1765 return 0; // Evolving from multiple different PHIs.
1766 }
1767
1768 // This is a expression evolving from a constant PHI!
1769 return PHI;
1770}
1771
1772/// EvaluateExpression - Given an expression that passes the
1773/// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
1774/// in the loop has the value PHIVal. If we can't fold this expression for some
1775/// reason, return null.
1776static Constant *EvaluateExpression(Value *V, Constant *PHIVal) {
1777 if (isa<PHINode>(V)) return PHIVal;
Chris Lattner3221ad02004-04-17 22:58:41 +00001778 if (GlobalValue *GV = dyn_cast<GlobalValue>(V))
Reid Spencere8404342004-07-18 00:18:30 +00001779 return GV;
1780 if (Constant *C = dyn_cast<Constant>(V)) return C;
Chris Lattner3221ad02004-04-17 22:58:41 +00001781 Instruction *I = cast<Instruction>(V);
1782
1783 std::vector<Constant*> Operands;
1784 Operands.resize(I->getNumOperands());
1785
1786 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
1787 Operands[i] = EvaluateExpression(I->getOperand(i), PHIVal);
1788 if (Operands[i] == 0) return 0;
1789 }
1790
1791 return ConstantFold(I, Operands);
1792}
1793
1794/// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
1795/// in the header of its containing loop, we know the loop executes a
1796/// constant number of times, and the PHI node is just a recurrence
1797/// involving constants, fold it.
1798Constant *ScalarEvolutionsImpl::
1799getConstantEvolutionLoopExitValue(PHINode *PN, uint64_t Its, const Loop *L) {
1800 std::map<PHINode*, Constant*>::iterator I =
1801 ConstantEvolutionLoopExitValue.find(PN);
1802 if (I != ConstantEvolutionLoopExitValue.end())
1803 return I->second;
1804
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001805 if (Its > MaxBruteForceIterations)
Chris Lattner3221ad02004-04-17 22:58:41 +00001806 return ConstantEvolutionLoopExitValue[PN] = 0; // Not going to evaluate it.
1807
1808 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
1809
1810 // Since the loop is canonicalized, the PHI node must have two entries. One
1811 // entry must be a constant (coming in from outside of the loop), and the
1812 // second must be derived from the same PHI.
1813 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
1814 Constant *StartCST =
1815 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
1816 if (StartCST == 0)
1817 return RetVal = 0; // Must be a constant.
1818
1819 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
1820 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
1821 if (PN2 != PN)
1822 return RetVal = 0; // Not derived from same PHI.
1823
1824 // Execute the loop symbolically to determine the exit value.
1825 unsigned IterationNum = 0;
1826 unsigned NumIterations = Its;
1827 if (NumIterations != Its)
1828 return RetVal = 0; // More than 2^32 iterations??
1829
1830 for (Constant *PHIVal = StartCST; ; ++IterationNum) {
1831 if (IterationNum == NumIterations)
1832 return RetVal = PHIVal; // Got exit value!
1833
1834 // Compute the value of the PHI node for the next iteration.
1835 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
1836 if (NextPHI == PHIVal)
1837 return RetVal = NextPHI; // Stopped evolving!
1838 if (NextPHI == 0)
1839 return 0; // Couldn't evaluate!
1840 PHIVal = NextPHI;
1841 }
1842}
1843
Chris Lattner7980fb92004-04-17 18:36:24 +00001844/// ComputeIterationCountExhaustively - If the trip is known to execute a
1845/// constant number of times (the condition evolves only from constants),
1846/// try to evaluate a few iterations of the loop until we get the exit
1847/// condition gets a value of ExitWhen (true or false). If we cannot
1848/// evaluate the trip count of the loop, return UnknownValue.
1849SCEVHandle ScalarEvolutionsImpl::
1850ComputeIterationCountExhaustively(const Loop *L, Value *Cond, bool ExitWhen) {
1851 PHINode *PN = getConstantEvolvingPHI(Cond, L);
1852 if (PN == 0) return UnknownValue;
1853
1854 // Since the loop is canonicalized, the PHI node must have two entries. One
1855 // entry must be a constant (coming in from outside of the loop), and the
1856 // second must be derived from the same PHI.
1857 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
1858 Constant *StartCST =
1859 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
1860 if (StartCST == 0) return UnknownValue; // Must be a constant.
1861
1862 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
1863 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
1864 if (PN2 != PN) return UnknownValue; // Not derived from same PHI.
1865
1866 // Okay, we find a PHI node that defines the trip count of this loop. Execute
1867 // the loop symbolically to determine when the condition gets a value of
1868 // "ExitWhen".
1869 unsigned IterationNum = 0;
1870 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis.
1871 for (Constant *PHIVal = StartCST;
1872 IterationNum != MaxIterations; ++IterationNum) {
1873 ConstantBool *CondVal =
1874 dyn_cast_or_null<ConstantBool>(EvaluateExpression(Cond, PHIVal));
1875 if (!CondVal) return UnknownValue; // Couldn't symbolically evaluate.
Chris Lattner3221ad02004-04-17 22:58:41 +00001876
Chris Lattner7980fb92004-04-17 18:36:24 +00001877 if (CondVal->getValue() == ExitWhen) {
Chris Lattner3221ad02004-04-17 22:58:41 +00001878 ConstantEvolutionLoopExitValue[PN] = PHIVal;
Chris Lattner7980fb92004-04-17 18:36:24 +00001879 ++NumBruteForceTripCountsComputed;
Reid Spencerb83eb642006-10-20 07:07:24 +00001880 return SCEVConstant::get(ConstantInt::get(Type::UIntTy, IterationNum));
Chris Lattner7980fb92004-04-17 18:36:24 +00001881 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001882
Chris Lattner3221ad02004-04-17 22:58:41 +00001883 // Compute the value of the PHI node for the next iteration.
1884 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
1885 if (NextPHI == 0 || NextPHI == PHIVal)
Chris Lattner7980fb92004-04-17 18:36:24 +00001886 return UnknownValue; // Couldn't evaluate or not making progress...
Chris Lattner3221ad02004-04-17 22:58:41 +00001887 PHIVal = NextPHI;
Chris Lattner7980fb92004-04-17 18:36:24 +00001888 }
1889
1890 // Too many iterations were needed to evaluate.
Chris Lattner53e677a2004-04-02 20:23:17 +00001891 return UnknownValue;
1892}
1893
1894/// getSCEVAtScope - Compute the value of the specified expression within the
1895/// indicated loop (which may be null to indicate in no loop). If the
1896/// expression cannot be evaluated, return UnknownValue.
1897SCEVHandle ScalarEvolutionsImpl::getSCEVAtScope(SCEV *V, const Loop *L) {
1898 // FIXME: this should be turned into a virtual method on SCEV!
1899
Chris Lattner3221ad02004-04-17 22:58:41 +00001900 if (isa<SCEVConstant>(V)) return V;
Misha Brukman2b37d7c2005-04-21 21:13:18 +00001901
Chris Lattner3221ad02004-04-17 22:58:41 +00001902 // If this instruction is evolves from a constant-evolving PHI, compute the
1903 // exit value from the loop without using SCEVs.
1904 if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
1905 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
1906 const Loop *LI = this->LI[I->getParent()];
1907 if (LI && LI->getParentLoop() == L) // Looking for loop exit value.
1908 if (PHINode *PN = dyn_cast<PHINode>(I))
1909 if (PN->getParent() == LI->getHeader()) {
1910 // Okay, there is no closed form solution for the PHI node. Check
1911 // to see if the loop that contains it has a known iteration count.
1912 // If so, we may be able to force computation of the exit value.
1913 SCEVHandle IterationCount = getIterationCount(LI);
1914 if (SCEVConstant *ICC = dyn_cast<SCEVConstant>(IterationCount)) {
1915 // Okay, we know how many times the containing loop executes. If
1916 // this is a constant evolving PHI node, get the final value at
1917 // the specified iteration number.
1918 Constant *RV = getConstantEvolutionLoopExitValue(PN,
Reid Spencerb83eb642006-10-20 07:07:24 +00001919 ICC->getValue()->getZExtValue(),
Chris Lattner3221ad02004-04-17 22:58:41 +00001920 LI);
1921 if (RV) return SCEVUnknown::get(RV);
1922 }
1923 }
1924
1925 // Okay, this is a some expression that we cannot symbolically evaluate
1926 // into a SCEV. Check to see if it's possible to symbolically evaluate
1927 // the arguments into constants, and if see, try to constant propagate the
1928 // result. This is particularly useful for computing loop exit values.
1929 if (CanConstantFold(I)) {
1930 std::vector<Constant*> Operands;
1931 Operands.reserve(I->getNumOperands());
1932 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
1933 Value *Op = I->getOperand(i);
1934 if (Constant *C = dyn_cast<Constant>(Op)) {
1935 Operands.push_back(C);
Chris Lattner3221ad02004-04-17 22:58:41 +00001936 } else {
1937 SCEVHandle OpV = getSCEVAtScope(getSCEV(Op), L);
1938 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(OpV))
1939 Operands.push_back(ConstantExpr::getCast(SC->getValue(),
1940 Op->getType()));
1941 else if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(OpV)) {
1942 if (Constant *C = dyn_cast<Constant>(SU->getValue()))
1943 Operands.push_back(ConstantExpr::getCast(C, Op->getType()));
1944 else
1945 return V;
1946 } else {
1947 return V;
1948 }
1949 }
1950 }
1951 return SCEVUnknown::get(ConstantFold(I, Operands));
1952 }
1953 }
1954
1955 // This is some other type of SCEVUnknown, just return it.
1956 return V;
1957 }
1958
Chris Lattner53e677a2004-04-02 20:23:17 +00001959 if (SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
1960 // Avoid performing the look-up in the common case where the specified
1961 // expression has no loop-variant portions.
1962 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
1963 SCEVHandle OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
1964 if (OpAtScope != Comm->getOperand(i)) {
1965 if (OpAtScope == UnknownValue) return UnknownValue;
1966 // Okay, at least one of these operands is loop variant but might be
1967 // foldable. Build a new instance of the folded commutative expression.
Chris Lattner3221ad02004-04-17 22:58:41 +00001968 std::vector<SCEVHandle> NewOps(Comm->op_begin(), Comm->op_begin()+i);
Chris Lattner53e677a2004-04-02 20:23:17 +00001969 NewOps.push_back(OpAtScope);
1970
1971 for (++i; i != e; ++i) {
1972 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
1973 if (OpAtScope == UnknownValue) return UnknownValue;
1974 NewOps.push_back(OpAtScope);
1975 }
1976 if (isa<SCEVAddExpr>(Comm))
1977 return SCEVAddExpr::get(NewOps);
1978 assert(isa<SCEVMulExpr>(Comm) && "Only know about add and mul!");
1979 return SCEVMulExpr::get(NewOps);
1980 }
1981 }
1982 // If we got here, all operands are loop invariant.
1983 return Comm;
1984 }
1985
Chris Lattner60a05cc2006-04-01 04:48:52 +00001986 if (SCEVSDivExpr *Div = dyn_cast<SCEVSDivExpr>(V)) {
1987 SCEVHandle LHS = getSCEVAtScope(Div->getLHS(), L);
Chris Lattner53e677a2004-04-02 20:23:17 +00001988 if (LHS == UnknownValue) return LHS;
Chris Lattner60a05cc2006-04-01 04:48:52 +00001989 SCEVHandle RHS = getSCEVAtScope(Div->getRHS(), L);
Chris Lattner53e677a2004-04-02 20:23:17 +00001990 if (RHS == UnknownValue) return RHS;
Chris Lattner60a05cc2006-04-01 04:48:52 +00001991 if (LHS == Div->getLHS() && RHS == Div->getRHS())
1992 return Div; // must be loop invariant
1993 return SCEVSDivExpr::get(LHS, RHS);
Chris Lattner53e677a2004-04-02 20:23:17 +00001994 }
1995
1996 // If this is a loop recurrence for a loop that does not contain L, then we
1997 // are dealing with the final value computed by the loop.
1998 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
1999 if (!L || !AddRec->getLoop()->contains(L->getHeader())) {
2000 // To evaluate this recurrence, we need to know how many times the AddRec
2001 // loop iterates. Compute this now.
2002 SCEVHandle IterationCount = getIterationCount(AddRec->getLoop());
2003 if (IterationCount == UnknownValue) return UnknownValue;
2004 IterationCount = getTruncateOrZeroExtend(IterationCount,
2005 AddRec->getType());
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002006
Chris Lattner53e677a2004-04-02 20:23:17 +00002007 // If the value is affine, simplify the expression evaluation to just
2008 // Start + Step*IterationCount.
2009 if (AddRec->isAffine())
2010 return SCEVAddExpr::get(AddRec->getStart(),
2011 SCEVMulExpr::get(IterationCount,
2012 AddRec->getOperand(1)));
2013
2014 // Otherwise, evaluate it the hard way.
2015 return AddRec->evaluateAtIteration(IterationCount);
2016 }
2017 return UnknownValue;
2018 }
2019
2020 //assert(0 && "Unknown SCEV type!");
2021 return UnknownValue;
2022}
2023
2024
2025/// SolveQuadraticEquation - Find the roots of the quadratic equation for the
2026/// given quadratic chrec {L,+,M,+,N}. This returns either the two roots (which
2027/// might be the same) or two SCEVCouldNotCompute objects.
2028///
2029static std::pair<SCEVHandle,SCEVHandle>
2030SolveQuadraticEquation(const SCEVAddRecExpr *AddRec) {
2031 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
2032 SCEVConstant *L = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
2033 SCEVConstant *M = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
2034 SCEVConstant *N = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002035
Chris Lattner53e677a2004-04-02 20:23:17 +00002036 // We currently can only solve this if the coefficients are constants.
2037 if (!L || !M || !N) {
2038 SCEV *CNC = new SCEVCouldNotCompute();
2039 return std::make_pair(CNC, CNC);
2040 }
2041
Reid Spencer1628cec2006-10-26 06:15:43 +00002042 Constant *C = L->getValue();
2043 Constant *Two = ConstantInt::get(C->getType(), 2);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002044
Chris Lattner53e677a2004-04-02 20:23:17 +00002045 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
Chris Lattner53e677a2004-04-02 20:23:17 +00002046 // The B coefficient is M-N/2
2047 Constant *B = ConstantExpr::getSub(M->getValue(),
Reid Spencer1628cec2006-10-26 06:15:43 +00002048 ConstantExpr::getSDiv(N->getValue(),
Chris Lattner53e677a2004-04-02 20:23:17 +00002049 Two));
2050 // The A coefficient is N/2
Reid Spencer1628cec2006-10-26 06:15:43 +00002051 Constant *A = ConstantExpr::getSDiv(N->getValue(), Two);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002052
Chris Lattner53e677a2004-04-02 20:23:17 +00002053 // Compute the B^2-4ac term.
2054 Constant *SqrtTerm =
2055 ConstantExpr::getMul(ConstantInt::get(C->getType(), 4),
2056 ConstantExpr::getMul(A, C));
2057 SqrtTerm = ConstantExpr::getSub(ConstantExpr::getMul(B, B), SqrtTerm);
2058
2059 // Compute floor(sqrt(B^2-4ac))
Reid Spencerb83eb642006-10-20 07:07:24 +00002060 ConstantInt *SqrtVal =
2061 cast<ConstantInt>(ConstantExpr::getCast(SqrtTerm,
Chris Lattner53e677a2004-04-02 20:23:17 +00002062 SqrtTerm->getType()->getUnsignedVersion()));
Reid Spencerb83eb642006-10-20 07:07:24 +00002063 uint64_t SqrtValV = SqrtVal->getZExtValue();
Chris Lattner219c1412004-10-25 18:40:08 +00002064 uint64_t SqrtValV2 = (uint64_t)sqrt((double)SqrtValV);
Chris Lattner53e677a2004-04-02 20:23:17 +00002065 // The square root might not be precise for arbitrary 64-bit integer
2066 // values. Do some sanity checks to ensure it's correct.
2067 if (SqrtValV2*SqrtValV2 > SqrtValV ||
2068 (SqrtValV2+1)*(SqrtValV2+1) <= SqrtValV) {
2069 SCEV *CNC = new SCEVCouldNotCompute();
2070 return std::make_pair(CNC, CNC);
2071 }
2072
Reid Spencerb83eb642006-10-20 07:07:24 +00002073 SqrtVal = ConstantInt::get(Type::ULongTy, SqrtValV2);
Chris Lattner53e677a2004-04-02 20:23:17 +00002074 SqrtTerm = ConstantExpr::getCast(SqrtVal, SqrtTerm->getType());
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002075
Chris Lattner53e677a2004-04-02 20:23:17 +00002076 Constant *NegB = ConstantExpr::getNeg(B);
2077 Constant *TwoA = ConstantExpr::getMul(A, Two);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002078
Chris Lattner53e677a2004-04-02 20:23:17 +00002079 // The divisions must be performed as signed divisions.
2080 const Type *SignedTy = NegB->getType()->getSignedVersion();
2081 NegB = ConstantExpr::getCast(NegB, SignedTy);
2082 TwoA = ConstantExpr::getCast(TwoA, SignedTy);
2083 SqrtTerm = ConstantExpr::getCast(SqrtTerm, SignedTy);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002084
Chris Lattner53e677a2004-04-02 20:23:17 +00002085 Constant *Solution1 =
Reid Spencer1628cec2006-10-26 06:15:43 +00002086 ConstantExpr::getSDiv(ConstantExpr::getAdd(NegB, SqrtTerm), TwoA);
Chris Lattner53e677a2004-04-02 20:23:17 +00002087 Constant *Solution2 =
Reid Spencer1628cec2006-10-26 06:15:43 +00002088 ConstantExpr::getSDiv(ConstantExpr::getSub(NegB, SqrtTerm), TwoA);
Chris Lattner53e677a2004-04-02 20:23:17 +00002089 return std::make_pair(SCEVUnknown::get(Solution1),
2090 SCEVUnknown::get(Solution2));
2091}
2092
2093/// HowFarToZero - Return the number of times a backedge comparing the specified
2094/// value to zero will execute. If not computable, return UnknownValue
2095SCEVHandle ScalarEvolutionsImpl::HowFarToZero(SCEV *V, const Loop *L) {
2096 // If the value is a constant
2097 if (SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
2098 // If the value is already zero, the branch will execute zero times.
2099 if (C->getValue()->isNullValue()) return C;
2100 return UnknownValue; // Otherwise it will loop infinitely.
2101 }
2102
2103 SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
2104 if (!AddRec || AddRec->getLoop() != L)
2105 return UnknownValue;
2106
2107 if (AddRec->isAffine()) {
2108 // If this is an affine expression the execution count of this branch is
2109 // equal to:
2110 //
2111 // (0 - Start/Step) iff Start % Step == 0
2112 //
2113 // Get the initial value for the loop.
2114 SCEVHandle Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
Chris Lattner4a2b23e2004-10-11 04:07:27 +00002115 if (isa<SCEVCouldNotCompute>(Start)) return UnknownValue;
Chris Lattner53e677a2004-04-02 20:23:17 +00002116 SCEVHandle Step = AddRec->getOperand(1);
2117
2118 Step = getSCEVAtScope(Step, L->getParentLoop());
2119
2120 // Figure out if Start % Step == 0.
2121 // FIXME: We should add DivExpr and RemExpr operations to our AST.
2122 if (SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step)) {
2123 if (StepC->getValue()->equalsInt(1)) // N % 1 == 0
Chris Lattnerbac5b462005-03-09 05:34:41 +00002124 return SCEV::getNegativeSCEV(Start); // 0 - Start/1 == -Start
Chris Lattner53e677a2004-04-02 20:23:17 +00002125 if (StepC->getValue()->isAllOnesValue()) // N % -1 == 0
2126 return Start; // 0 - Start/-1 == Start
2127
2128 // Check to see if Start is divisible by SC with no remainder.
2129 if (SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start)) {
2130 ConstantInt *StartCC = StartC->getValue();
2131 Constant *StartNegC = ConstantExpr::getNeg(StartCC);
Reid Spencer0a783f72006-11-02 01:53:59 +00002132 Constant *Rem = ConstantExpr::getSRem(StartNegC, StepC->getValue());
Chris Lattner53e677a2004-04-02 20:23:17 +00002133 if (Rem->isNullValue()) {
Reid Spencer1628cec2006-10-26 06:15:43 +00002134 Constant *Result =ConstantExpr::getSDiv(StartNegC,StepC->getValue());
Chris Lattner53e677a2004-04-02 20:23:17 +00002135 return SCEVUnknown::get(Result);
2136 }
2137 }
2138 }
2139 } else if (AddRec->isQuadratic() && AddRec->getType()->isInteger()) {
2140 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
2141 // the quadratic equation to solve it.
2142 std::pair<SCEVHandle,SCEVHandle> Roots = SolveQuadraticEquation(AddRec);
2143 SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
2144 SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
2145 if (R1) {
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00002146#if 0
Bill Wendling6f81b512006-11-28 22:46:12 +00002147 llvm_cerr << "HFTZ: " << *V << " - sol#1: " << *R1
Chris Lattner53e677a2004-04-02 20:23:17 +00002148 << " sol#2: " << *R2 << "\n";
Chris Lattnerd18d9dc2004-04-02 20:26:46 +00002149#endif
Chris Lattner53e677a2004-04-02 20:23:17 +00002150 // Pick the smallest positive root value.
2151 assert(R1->getType()->isUnsigned()&&"Didn't canonicalize to unsigned?");
2152 if (ConstantBool *CB =
2153 dyn_cast<ConstantBool>(ConstantExpr::getSetLT(R1->getValue(),
2154 R2->getValue()))) {
Chris Lattner003cbf32006-09-28 23:36:21 +00002155 if (CB->getValue() == false)
Chris Lattner53e677a2004-04-02 20:23:17 +00002156 std::swap(R1, R2); // R1 is the minimum root now.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002157
Chris Lattner53e677a2004-04-02 20:23:17 +00002158 // We can only use this value if the chrec ends up with an exact zero
2159 // value at this index. When solving for "X*X != 5", for example, we
2160 // should not accept a root of 2.
2161 SCEVHandle Val = AddRec->evaluateAtIteration(R1);
2162 if (SCEVConstant *EvalVal = dyn_cast<SCEVConstant>(Val))
2163 if (EvalVal->getValue()->isNullValue())
2164 return R1; // We found a quadratic root!
2165 }
2166 }
2167 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002168
Chris Lattner53e677a2004-04-02 20:23:17 +00002169 return UnknownValue;
2170}
2171
2172/// HowFarToNonZero - Return the number of times a backedge checking the
2173/// specified value for nonzero will execute. If not computable, return
2174/// UnknownValue
2175SCEVHandle ScalarEvolutionsImpl::HowFarToNonZero(SCEV *V, const Loop *L) {
2176 // Loops that look like: while (X == 0) are very strange indeed. We don't
2177 // handle them yet except for the trivial case. This could be expanded in the
2178 // future as needed.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002179
Chris Lattner53e677a2004-04-02 20:23:17 +00002180 // If the value is a constant, check to see if it is known to be non-zero
2181 // already. If so, the backedge will execute zero times.
2182 if (SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
2183 Constant *Zero = Constant::getNullValue(C->getValue()->getType());
2184 Constant *NonZero = ConstantExpr::getSetNE(C->getValue(), Zero);
Chris Lattner003cbf32006-09-28 23:36:21 +00002185 if (NonZero == ConstantBool::getTrue())
Chris Lattner53e677a2004-04-02 20:23:17 +00002186 return getSCEV(Zero);
2187 return UnknownValue; // Otherwise it will loop infinitely.
2188 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002189
Chris Lattner53e677a2004-04-02 20:23:17 +00002190 // We could implement others, but I really doubt anyone writes loops like
2191 // this, and if they did, they would already be constant folded.
2192 return UnknownValue;
2193}
2194
Chris Lattnerdb25de42005-08-15 23:33:51 +00002195/// HowManyLessThans - Return the number of times a backedge containing the
2196/// specified less-than comparison will execute. If not computable, return
2197/// UnknownValue.
2198SCEVHandle ScalarEvolutionsImpl::
2199HowManyLessThans(SCEV *LHS, SCEV *RHS, const Loop *L) {
2200 // Only handle: "ADDREC < LoopInvariant".
2201 if (!RHS->isLoopInvariant(L)) return UnknownValue;
2202
2203 SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS);
2204 if (!AddRec || AddRec->getLoop() != L)
2205 return UnknownValue;
2206
2207 if (AddRec->isAffine()) {
2208 // FORNOW: We only support unit strides.
2209 SCEVHandle One = SCEVUnknown::getIntegerSCEV(1, RHS->getType());
2210 if (AddRec->getOperand(1) != One)
2211 return UnknownValue;
2212
2213 // The number of iterations for "[n,+,1] < m", is m-n. However, we don't
2214 // know that m is >= n on input to the loop. If it is, the condition return
2215 // true zero times. What we really should return, for full generality, is
2216 // SMAX(0, m-n). Since we cannot check this, we will instead check for a
2217 // canonical loop form: most do-loops will have a check that dominates the
2218 // loop, that only enters the loop if [n-1]<m. If we can find this check,
2219 // we know that the SMAX will evaluate to m-n, because we know that m >= n.
2220
2221 // Search for the check.
2222 BasicBlock *Preheader = L->getLoopPreheader();
2223 BasicBlock *PreheaderDest = L->getHeader();
2224 if (Preheader == 0) return UnknownValue;
2225
2226 BranchInst *LoopEntryPredicate =
2227 dyn_cast<BranchInst>(Preheader->getTerminator());
2228 if (!LoopEntryPredicate) return UnknownValue;
2229
2230 // This might be a critical edge broken out. If the loop preheader ends in
2231 // an unconditional branch to the loop, check to see if the preheader has a
2232 // single predecessor, and if so, look for its terminator.
2233 while (LoopEntryPredicate->isUnconditional()) {
2234 PreheaderDest = Preheader;
2235 Preheader = Preheader->getSinglePredecessor();
2236 if (!Preheader) return UnknownValue; // Multiple preds.
2237
2238 LoopEntryPredicate =
2239 dyn_cast<BranchInst>(Preheader->getTerminator());
2240 if (!LoopEntryPredicate) return UnknownValue;
2241 }
2242
2243 // Now that we found a conditional branch that dominates the loop, check to
2244 // see if it is the comparison we are looking for.
2245 SetCondInst *SCI =dyn_cast<SetCondInst>(LoopEntryPredicate->getCondition());
2246 if (!SCI) return UnknownValue;
2247 Value *PreCondLHS = SCI->getOperand(0);
2248 Value *PreCondRHS = SCI->getOperand(1);
2249 Instruction::BinaryOps Cond;
2250 if (LoopEntryPredicate->getSuccessor(0) == PreheaderDest)
2251 Cond = SCI->getOpcode();
2252 else
2253 Cond = SCI->getInverseCondition();
2254
2255 switch (Cond) {
2256 case Instruction::SetGT:
2257 std::swap(PreCondLHS, PreCondRHS);
2258 Cond = Instruction::SetLT;
2259 // Fall Through.
2260 case Instruction::SetLT:
2261 if (PreCondLHS->getType()->isInteger() &&
2262 PreCondLHS->getType()->isSigned()) {
2263 if (RHS != getSCEV(PreCondRHS))
2264 return UnknownValue; // Not a comparison against 'm'.
2265
2266 if (SCEV::getMinusSCEV(AddRec->getOperand(0), One)
2267 != getSCEV(PreCondLHS))
2268 return UnknownValue; // Not a comparison against 'n-1'.
2269 break;
2270 } else {
2271 return UnknownValue;
2272 }
2273 default: break;
2274 }
2275
Bill Wendling6f81b512006-11-28 22:46:12 +00002276 //llvm_cerr << "Computed Loop Trip Count as: " <<
Chris Lattnerdb25de42005-08-15 23:33:51 +00002277 // *SCEV::getMinusSCEV(RHS, AddRec->getOperand(0)) << "\n";
2278 return SCEV::getMinusSCEV(RHS, AddRec->getOperand(0));
2279 }
2280
2281 return UnknownValue;
2282}
2283
Chris Lattner53e677a2004-04-02 20:23:17 +00002284/// getNumIterationsInRange - Return the number of iterations of this loop that
2285/// produce values in the specified constant range. Another way of looking at
2286/// this is that it returns the first iteration number where the value is not in
2287/// the condition, thus computing the exit count. If the iteration count can't
2288/// be computed, an instance of SCEVCouldNotCompute is returned.
2289SCEVHandle SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range) const {
2290 if (Range.isFullSet()) // Infinite loop.
2291 return new SCEVCouldNotCompute();
2292
2293 // If the start is a non-zero constant, shift the range to simplify things.
2294 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
2295 if (!SC->getValue()->isNullValue()) {
2296 std::vector<SCEVHandle> Operands(op_begin(), op_end());
Chris Lattnerb06432c2004-04-23 21:29:03 +00002297 Operands[0] = SCEVUnknown::getIntegerSCEV(0, SC->getType());
Chris Lattner53e677a2004-04-02 20:23:17 +00002298 SCEVHandle Shifted = SCEVAddRecExpr::get(Operands, getLoop());
2299 if (SCEVAddRecExpr *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted))
2300 return ShiftedAddRec->getNumIterationsInRange(
2301 Range.subtract(SC->getValue()));
2302 // This is strange and shouldn't happen.
2303 return new SCEVCouldNotCompute();
2304 }
2305
2306 // The only time we can solve this is when we have all constant indices.
2307 // Otherwise, we cannot determine the overflow conditions.
2308 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
2309 if (!isa<SCEVConstant>(getOperand(i)))
2310 return new SCEVCouldNotCompute();
2311
2312
2313 // Okay at this point we know that all elements of the chrec are constants and
2314 // that the start element is zero.
2315
2316 // First check to see if the range contains zero. If not, the first
2317 // iteration exits.
2318 ConstantInt *Zero = ConstantInt::get(getType(), 0);
2319 if (!Range.contains(Zero)) return SCEVConstant::get(Zero);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002320
Chris Lattner53e677a2004-04-02 20:23:17 +00002321 if (isAffine()) {
2322 // If this is an affine expression then we have this situation:
2323 // Solve {0,+,A} in Range === Ax in Range
2324
2325 // Since we know that zero is in the range, we know that the upper value of
2326 // the range must be the first possible exit value. Also note that we
2327 // already checked for a full range.
2328 ConstantInt *Upper = cast<ConstantInt>(Range.getUpper());
2329 ConstantInt *A = cast<SCEVConstant>(getOperand(1))->getValue();
2330 ConstantInt *One = ConstantInt::get(getType(), 1);
2331
2332 // The exit value should be (Upper+A-1)/A.
2333 Constant *ExitValue = Upper;
2334 if (A != One) {
2335 ExitValue = ConstantExpr::getSub(ConstantExpr::getAdd(Upper, A), One);
Reid Spencer1628cec2006-10-26 06:15:43 +00002336 ExitValue = ConstantExpr::getSDiv(ExitValue, A);
Chris Lattner53e677a2004-04-02 20:23:17 +00002337 }
2338 assert(isa<ConstantInt>(ExitValue) &&
2339 "Constant folding of integers not implemented?");
2340
2341 // Evaluate at the exit value. If we really did fall out of the valid
2342 // range, then we computed our trip count, otherwise wrap around or other
2343 // things must have happened.
2344 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue);
2345 if (Range.contains(Val))
2346 return new SCEVCouldNotCompute(); // Something strange happened
2347
2348 // Ensure that the previous value is in the range. This is a sanity check.
2349 assert(Range.contains(EvaluateConstantChrecAtConstant(this,
2350 ConstantExpr::getSub(ExitValue, One))) &&
2351 "Linear scev computation is off in a bad way!");
2352 return SCEVConstant::get(cast<ConstantInt>(ExitValue));
2353 } else if (isQuadratic()) {
2354 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
2355 // quadratic equation to solve it. To do this, we must frame our problem in
2356 // terms of figuring out when zero is crossed, instead of when
2357 // Range.getUpper() is crossed.
2358 std::vector<SCEVHandle> NewOps(op_begin(), op_end());
Chris Lattnerbac5b462005-03-09 05:34:41 +00002359 NewOps[0] = SCEV::getNegativeSCEV(SCEVUnknown::get(Range.getUpper()));
Chris Lattner53e677a2004-04-02 20:23:17 +00002360 SCEVHandle NewAddRec = SCEVAddRecExpr::get(NewOps, getLoop());
2361
2362 // Next, solve the constructed addrec
2363 std::pair<SCEVHandle,SCEVHandle> Roots =
2364 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec));
2365 SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
2366 SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
2367 if (R1) {
2368 // Pick the smallest positive root value.
2369 assert(R1->getType()->isUnsigned() && "Didn't canonicalize to unsigned?");
2370 if (ConstantBool *CB =
2371 dyn_cast<ConstantBool>(ConstantExpr::getSetLT(R1->getValue(),
2372 R2->getValue()))) {
Chris Lattner003cbf32006-09-28 23:36:21 +00002373 if (CB->getValue() == false)
Chris Lattner53e677a2004-04-02 20:23:17 +00002374 std::swap(R1, R2); // R1 is the minimum root now.
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002375
Chris Lattner53e677a2004-04-02 20:23:17 +00002376 // Make sure the root is not off by one. The returned iteration should
2377 // not be in the range, but the previous one should be. When solving
2378 // for "X*X < 5", for example, we should not return a root of 2.
2379 ConstantInt *R1Val = EvaluateConstantChrecAtConstant(this,
2380 R1->getValue());
2381 if (Range.contains(R1Val)) {
2382 // The next iteration must be out of the range...
2383 Constant *NextVal =
2384 ConstantExpr::getAdd(R1->getValue(),
2385 ConstantInt::get(R1->getType(), 1));
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002386
Chris Lattner53e677a2004-04-02 20:23:17 +00002387 R1Val = EvaluateConstantChrecAtConstant(this, NextVal);
2388 if (!Range.contains(R1Val))
2389 return SCEVUnknown::get(NextVal);
2390 return new SCEVCouldNotCompute(); // Something strange happened
2391 }
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002392
Chris Lattner53e677a2004-04-02 20:23:17 +00002393 // If R1 was not in the range, then it is a good return value. Make
2394 // sure that R1-1 WAS in the range though, just in case.
2395 Constant *NextVal =
2396 ConstantExpr::getSub(R1->getValue(),
2397 ConstantInt::get(R1->getType(), 1));
2398 R1Val = EvaluateConstantChrecAtConstant(this, NextVal);
2399 if (Range.contains(R1Val))
2400 return R1;
2401 return new SCEVCouldNotCompute(); // Something strange happened
2402 }
2403 }
2404 }
2405
2406 // Fallback, if this is a general polynomial, figure out the progression
2407 // through brute force: evaluate until we find an iteration that fails the
2408 // test. This is likely to be slow, but getting an accurate trip count is
2409 // incredibly important, we will be able to simplify the exit test a lot, and
2410 // we are almost guaranteed to get a trip count in this case.
2411 ConstantInt *TestVal = ConstantInt::get(getType(), 0);
2412 ConstantInt *One = ConstantInt::get(getType(), 1);
2413 ConstantInt *EndVal = TestVal; // Stop when we wrap around.
2414 do {
2415 ++NumBruteForceEvaluations;
2416 SCEVHandle Val = evaluateAtIteration(SCEVConstant::get(TestVal));
2417 if (!isa<SCEVConstant>(Val)) // This shouldn't happen.
2418 return new SCEVCouldNotCompute();
2419
2420 // Check to see if we found the value!
2421 if (!Range.contains(cast<SCEVConstant>(Val)->getValue()))
2422 return SCEVConstant::get(TestVal);
2423
2424 // Increment to test the next index.
2425 TestVal = cast<ConstantInt>(ConstantExpr::getAdd(TestVal, One));
2426 } while (TestVal != EndVal);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002427
Chris Lattner53e677a2004-04-02 20:23:17 +00002428 return new SCEVCouldNotCompute();
2429}
2430
2431
2432
2433//===----------------------------------------------------------------------===//
2434// ScalarEvolution Class Implementation
2435//===----------------------------------------------------------------------===//
2436
2437bool ScalarEvolution::runOnFunction(Function &F) {
2438 Impl = new ScalarEvolutionsImpl(F, getAnalysis<LoopInfo>());
2439 return false;
2440}
2441
2442void ScalarEvolution::releaseMemory() {
2443 delete (ScalarEvolutionsImpl*)Impl;
2444 Impl = 0;
2445}
2446
2447void ScalarEvolution::getAnalysisUsage(AnalysisUsage &AU) const {
2448 AU.setPreservesAll();
Chris Lattner53e677a2004-04-02 20:23:17 +00002449 AU.addRequiredTransitive<LoopInfo>();
2450}
2451
2452SCEVHandle ScalarEvolution::getSCEV(Value *V) const {
2453 return ((ScalarEvolutionsImpl*)Impl)->getSCEV(V);
2454}
2455
Chris Lattnera0740fb2005-08-09 23:36:33 +00002456/// hasSCEV - Return true if the SCEV for this value has already been
2457/// computed.
2458bool ScalarEvolution::hasSCEV(Value *V) const {
Chris Lattner05bd3742005-08-10 00:59:40 +00002459 return ((ScalarEvolutionsImpl*)Impl)->hasSCEV(V);
Chris Lattnera0740fb2005-08-09 23:36:33 +00002460}
2461
2462
2463/// setSCEV - Insert the specified SCEV into the map of current SCEVs for
2464/// the specified value.
2465void ScalarEvolution::setSCEV(Value *V, const SCEVHandle &H) {
2466 ((ScalarEvolutionsImpl*)Impl)->setSCEV(V, H);
2467}
2468
2469
Chris Lattner53e677a2004-04-02 20:23:17 +00002470SCEVHandle ScalarEvolution::getIterationCount(const Loop *L) const {
2471 return ((ScalarEvolutionsImpl*)Impl)->getIterationCount(L);
2472}
2473
2474bool ScalarEvolution::hasLoopInvariantIterationCount(const Loop *L) const {
2475 return !isa<SCEVCouldNotCompute>(getIterationCount(L));
2476}
2477
2478SCEVHandle ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) const {
2479 return ((ScalarEvolutionsImpl*)Impl)->getSCEVAtScope(getSCEV(V), L);
2480}
2481
2482void ScalarEvolution::deleteInstructionFromRecords(Instruction *I) const {
2483 return ((ScalarEvolutionsImpl*)Impl)->deleteInstructionFromRecords(I);
2484}
2485
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002486static void PrintLoopInfo(std::ostream &OS, const ScalarEvolution *SE,
Chris Lattner53e677a2004-04-02 20:23:17 +00002487 const Loop *L) {
2488 // Print all inner loops first
2489 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
2490 PrintLoopInfo(OS, SE, *I);
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002491
Bill Wendling6f81b512006-11-28 22:46:12 +00002492 llvm_cerr << "Loop " << L->getHeader()->getName() << ": ";
Chris Lattnerf1ab4b42004-04-18 22:14:10 +00002493
2494 std::vector<BasicBlock*> ExitBlocks;
2495 L->getExitBlocks(ExitBlocks);
2496 if (ExitBlocks.size() != 1)
Bill Wendling6f81b512006-11-28 22:46:12 +00002497 llvm_cerr << "<multiple exits> ";
Chris Lattner53e677a2004-04-02 20:23:17 +00002498
2499 if (SE->hasLoopInvariantIterationCount(L)) {
Bill Wendling6f81b512006-11-28 22:46:12 +00002500 llvm_cerr << *SE->getIterationCount(L) << " iterations! ";
Chris Lattner53e677a2004-04-02 20:23:17 +00002501 } else {
Bill Wendling6f81b512006-11-28 22:46:12 +00002502 llvm_cerr << "Unpredictable iteration count. ";
Chris Lattner53e677a2004-04-02 20:23:17 +00002503 }
2504
Bill Wendling6f81b512006-11-28 22:46:12 +00002505 llvm_cerr << "\n";
Chris Lattner53e677a2004-04-02 20:23:17 +00002506}
2507
Reid Spencerce9653c2004-12-07 04:03:45 +00002508void ScalarEvolution::print(std::ostream &OS, const Module* ) const {
Chris Lattner53e677a2004-04-02 20:23:17 +00002509 Function &F = ((ScalarEvolutionsImpl*)Impl)->F;
2510 LoopInfo &LI = ((ScalarEvolutionsImpl*)Impl)->LI;
2511
2512 OS << "Classifying expressions for: " << F.getName() << "\n";
2513 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
Chris Lattner6ffe5512004-04-27 15:13:33 +00002514 if (I->getType()->isInteger()) {
2515 OS << *I;
Chris Lattner53e677a2004-04-02 20:23:17 +00002516 OS << " --> ";
Chris Lattner6ffe5512004-04-27 15:13:33 +00002517 SCEVHandle SV = getSCEV(&*I);
Chris Lattner53e677a2004-04-02 20:23:17 +00002518 SV->print(OS);
2519 OS << "\t\t";
Misha Brukman2b37d7c2005-04-21 21:13:18 +00002520
Chris Lattner6ffe5512004-04-27 15:13:33 +00002521 if ((*I).getType()->isIntegral()) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002522 ConstantRange Bounds = SV->getValueRange();
2523 if (!Bounds.isFullSet())
2524 OS << "Bounds: " << Bounds << " ";
2525 }
2526
Chris Lattner6ffe5512004-04-27 15:13:33 +00002527 if (const Loop *L = LI.getLoopFor((*I).getParent())) {
Chris Lattner53e677a2004-04-02 20:23:17 +00002528 OS << "Exits: ";
Chris Lattner6ffe5512004-04-27 15:13:33 +00002529 SCEVHandle ExitValue = getSCEVAtScope(&*I, L->getParentLoop());
Chris Lattner53e677a2004-04-02 20:23:17 +00002530 if (isa<SCEVCouldNotCompute>(ExitValue)) {
2531 OS << "<<Unknown>>";
2532 } else {
2533 OS << *ExitValue;
2534 }
2535 }
2536
2537
2538 OS << "\n";
2539 }
2540
2541 OS << "Determining loop execution counts for: " << F.getName() << "\n";
2542 for (LoopInfo::iterator I = LI.begin(), E = LI.end(); I != E; ++I)
2543 PrintLoopInfo(OS, this, *I);
2544}
2545