blob: ab0de275b04df75e73bf8b46fbd90542e81bf512 [file] [log] [blame]
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001//===- ScalarEvolution.cpp - Scalar Evolution Analysis ----------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner081ce942007-12-29 20:36:04 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00007//
8//===----------------------------------------------------------------------===//
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.
31//
32// 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//
36// 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
62#define DEBUG_TYPE "scalar-evolution"
63#include "llvm/Analysis/ScalarEvolutionExpressions.h"
64#include "llvm/Constants.h"
65#include "llvm/DerivedTypes.h"
66#include "llvm/GlobalVariable.h"
67#include "llvm/Instructions.h"
68#include "llvm/Analysis/ConstantFolding.h"
69#include "llvm/Analysis/LoopInfo.h"
70#include "llvm/Assembly/Writer.h"
71#include "llvm/Transforms/Scalar.h"
72#include "llvm/Support/CFG.h"
73#include "llvm/Support/CommandLine.h"
74#include "llvm/Support/Compiler.h"
75#include "llvm/Support/ConstantRange.h"
76#include "llvm/Support/InstIterator.h"
77#include "llvm/Support/ManagedStatic.h"
78#include "llvm/Support/MathExtras.h"
79#include "llvm/Support/Streams.h"
80#include "llvm/ADT/Statistic.h"
81#include <ostream>
82#include <algorithm>
83#include <cmath>
84using namespace llvm;
85
86STATISTIC(NumBruteForceEvaluations,
87 "Number of brute force evaluations needed to "
88 "calculate high-order polynomial exit values");
89STATISTIC(NumArrayLenItCounts,
90 "Number of trip counts computed with array length");
91STATISTIC(NumTripCountsComputed,
92 "Number of loops with predictable loop counts");
93STATISTIC(NumTripCountsNotComputed,
94 "Number of loops without predictable loop counts");
95STATISTIC(NumBruteForceTripCountsComputed,
96 "Number of loops with trip counts computed by force");
97
Dan Gohman089efff2008-05-13 00:00:25 +000098static cl::opt<unsigned>
Dan Gohmanf17a25c2007-07-18 16:29:46 +000099MaxBruteForceIterations("scalar-evolution-max-iterations", cl::ReallyHidden,
100 cl::desc("Maximum number of iterations SCEV will "
101 "symbolically execute a constant derived loop"),
102 cl::init(100));
103
Dan Gohman089efff2008-05-13 00:00:25 +0000104static RegisterPass<ScalarEvolution>
105R("scalar-evolution", "Scalar Evolution Analysis", false, true);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000106char ScalarEvolution::ID = 0;
107
108//===----------------------------------------------------------------------===//
109// SCEV class definitions
110//===----------------------------------------------------------------------===//
111
112//===----------------------------------------------------------------------===//
113// Implementation of the SCEV class.
114//
115SCEV::~SCEV() {}
116void SCEV::dump() const {
117 print(cerr);
118}
119
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000120uint32_t SCEV::getBitWidth() const {
121 if (const IntegerType* ITy = dyn_cast<IntegerType>(getType()))
122 return ITy->getBitWidth();
123 return 0;
124}
125
Dan Gohman7b560c42008-06-18 16:23:07 +0000126bool SCEV::isZero() const {
127 if (const SCEVConstant *SC = dyn_cast<SCEVConstant>(this))
128 return SC->getValue()->isZero();
129 return false;
130}
131
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000132
133SCEVCouldNotCompute::SCEVCouldNotCompute() : SCEV(scCouldNotCompute) {}
134
135bool SCEVCouldNotCompute::isLoopInvariant(const Loop *L) const {
136 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
137 return false;
138}
139
140const Type *SCEVCouldNotCompute::getType() const {
141 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
142 return 0;
143}
144
145bool SCEVCouldNotCompute::hasComputableLoopEvolution(const Loop *L) const {
146 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
147 return false;
148}
149
150SCEVHandle SCEVCouldNotCompute::
151replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
Dan Gohman89f85052007-10-22 18:31:58 +0000152 const SCEVHandle &Conc,
153 ScalarEvolution &SE) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000154 return this;
155}
156
157void SCEVCouldNotCompute::print(std::ostream &OS) const {
158 OS << "***COULDNOTCOMPUTE***";
159}
160
161bool SCEVCouldNotCompute::classof(const SCEV *S) {
162 return S->getSCEVType() == scCouldNotCompute;
163}
164
165
166// SCEVConstants - Only allow the creation of one SCEVConstant for any
167// particular value. Don't use a SCEVHandle here, or else the object will
168// never be deleted!
169static ManagedStatic<std::map<ConstantInt*, SCEVConstant*> > SCEVConstants;
170
171
172SCEVConstant::~SCEVConstant() {
173 SCEVConstants->erase(V);
174}
175
Dan Gohman89f85052007-10-22 18:31:58 +0000176SCEVHandle ScalarEvolution::getConstant(ConstantInt *V) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000177 SCEVConstant *&R = (*SCEVConstants)[V];
178 if (R == 0) R = new SCEVConstant(V);
179 return R;
180}
181
Dan Gohman89f85052007-10-22 18:31:58 +0000182SCEVHandle ScalarEvolution::getConstant(const APInt& Val) {
183 return getConstant(ConstantInt::get(Val));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000184}
185
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000186const Type *SCEVConstant::getType() const { return V->getType(); }
187
188void SCEVConstant::print(std::ostream &OS) const {
189 WriteAsOperand(OS, V, false);
190}
191
192// SCEVTruncates - Only allow the creation of one SCEVTruncateExpr for any
193// particular input. Don't use a SCEVHandle here, or else the object will
194// never be deleted!
195static ManagedStatic<std::map<std::pair<SCEV*, const Type*>,
196 SCEVTruncateExpr*> > SCEVTruncates;
197
198SCEVTruncateExpr::SCEVTruncateExpr(const SCEVHandle &op, const Type *ty)
199 : SCEV(scTruncate), Op(op), Ty(ty) {
200 assert(Op->getType()->isInteger() && Ty->isInteger() &&
201 "Cannot truncate non-integer value!");
202 assert(Op->getType()->getPrimitiveSizeInBits() > Ty->getPrimitiveSizeInBits()
203 && "This is not a truncating conversion!");
204}
205
206SCEVTruncateExpr::~SCEVTruncateExpr() {
207 SCEVTruncates->erase(std::make_pair(Op, Ty));
208}
209
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000210void SCEVTruncateExpr::print(std::ostream &OS) const {
211 OS << "(truncate " << *Op << " to " << *Ty << ")";
212}
213
214// SCEVZeroExtends - Only allow the creation of one SCEVZeroExtendExpr for any
215// particular input. Don't use a SCEVHandle here, or else the object will never
216// be deleted!
217static ManagedStatic<std::map<std::pair<SCEV*, const Type*>,
218 SCEVZeroExtendExpr*> > SCEVZeroExtends;
219
220SCEVZeroExtendExpr::SCEVZeroExtendExpr(const SCEVHandle &op, const Type *ty)
221 : SCEV(scZeroExtend), Op(op), Ty(ty) {
222 assert(Op->getType()->isInteger() && Ty->isInteger() &&
223 "Cannot zero extend non-integer value!");
224 assert(Op->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits()
225 && "This is not an extending conversion!");
226}
227
228SCEVZeroExtendExpr::~SCEVZeroExtendExpr() {
229 SCEVZeroExtends->erase(std::make_pair(Op, Ty));
230}
231
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000232void SCEVZeroExtendExpr::print(std::ostream &OS) const {
233 OS << "(zeroextend " << *Op << " to " << *Ty << ")";
234}
235
236// SCEVSignExtends - Only allow the creation of one SCEVSignExtendExpr for any
237// particular input. Don't use a SCEVHandle here, or else the object will never
238// be deleted!
239static ManagedStatic<std::map<std::pair<SCEV*, const Type*>,
240 SCEVSignExtendExpr*> > SCEVSignExtends;
241
242SCEVSignExtendExpr::SCEVSignExtendExpr(const SCEVHandle &op, const Type *ty)
243 : SCEV(scSignExtend), Op(op), Ty(ty) {
244 assert(Op->getType()->isInteger() && Ty->isInteger() &&
245 "Cannot sign extend non-integer value!");
246 assert(Op->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits()
247 && "This is not an extending conversion!");
248}
249
250SCEVSignExtendExpr::~SCEVSignExtendExpr() {
251 SCEVSignExtends->erase(std::make_pair(Op, Ty));
252}
253
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000254void SCEVSignExtendExpr::print(std::ostream &OS) const {
255 OS << "(signextend " << *Op << " to " << *Ty << ")";
256}
257
258// SCEVCommExprs - Only allow the creation of one SCEVCommutativeExpr for any
259// particular input. Don't use a SCEVHandle here, or else the object will never
260// be deleted!
261static ManagedStatic<std::map<std::pair<unsigned, std::vector<SCEV*> >,
262 SCEVCommutativeExpr*> > SCEVCommExprs;
263
264SCEVCommutativeExpr::~SCEVCommutativeExpr() {
265 SCEVCommExprs->erase(std::make_pair(getSCEVType(),
266 std::vector<SCEV*>(Operands.begin(),
267 Operands.end())));
268}
269
270void SCEVCommutativeExpr::print(std::ostream &OS) const {
271 assert(Operands.size() > 1 && "This plus expr shouldn't exist!");
272 const char *OpStr = getOperationStr();
273 OS << "(" << *Operands[0];
274 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
275 OS << OpStr << *Operands[i];
276 OS << ")";
277}
278
279SCEVHandle SCEVCommutativeExpr::
280replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
Dan Gohman89f85052007-10-22 18:31:58 +0000281 const SCEVHandle &Conc,
282 ScalarEvolution &SE) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000283 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
Dan Gohman89f85052007-10-22 18:31:58 +0000284 SCEVHandle H =
285 getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000286 if (H != getOperand(i)) {
287 std::vector<SCEVHandle> NewOps;
288 NewOps.reserve(getNumOperands());
289 for (unsigned j = 0; j != i; ++j)
290 NewOps.push_back(getOperand(j));
291 NewOps.push_back(H);
292 for (++i; i != e; ++i)
293 NewOps.push_back(getOperand(i)->
Dan Gohman89f85052007-10-22 18:31:58 +0000294 replaceSymbolicValuesWithConcrete(Sym, Conc, SE));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000295
296 if (isa<SCEVAddExpr>(this))
Dan Gohman89f85052007-10-22 18:31:58 +0000297 return SE.getAddExpr(NewOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000298 else if (isa<SCEVMulExpr>(this))
Dan Gohman89f85052007-10-22 18:31:58 +0000299 return SE.getMulExpr(NewOps);
Nick Lewycky711640a2007-11-25 22:41:31 +0000300 else if (isa<SCEVSMaxExpr>(this))
301 return SE.getSMaxExpr(NewOps);
Nick Lewyckye7a24ff2008-02-20 06:48:22 +0000302 else if (isa<SCEVUMaxExpr>(this))
303 return SE.getUMaxExpr(NewOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000304 else
305 assert(0 && "Unknown commutative expr!");
306 }
307 }
308 return this;
309}
310
311
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000312// SCEVUDivs - Only allow the creation of one SCEVUDivExpr for any particular
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000313// input. Don't use a SCEVHandle here, or else the object will never be
314// deleted!
315static ManagedStatic<std::map<std::pair<SCEV*, SCEV*>,
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000316 SCEVUDivExpr*> > SCEVUDivs;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000317
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000318SCEVUDivExpr::~SCEVUDivExpr() {
319 SCEVUDivs->erase(std::make_pair(LHS, RHS));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000320}
321
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000322void SCEVUDivExpr::print(std::ostream &OS) const {
323 OS << "(" << *LHS << " /u " << *RHS << ")";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000324}
325
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000326const Type *SCEVUDivExpr::getType() const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000327 return LHS->getType();
328}
329
330// SCEVAddRecExprs - Only allow the creation of one SCEVAddRecExpr for any
331// particular input. Don't use a SCEVHandle here, or else the object will never
332// be deleted!
333static ManagedStatic<std::map<std::pair<const Loop *, std::vector<SCEV*> >,
334 SCEVAddRecExpr*> > SCEVAddRecExprs;
335
336SCEVAddRecExpr::~SCEVAddRecExpr() {
337 SCEVAddRecExprs->erase(std::make_pair(L,
338 std::vector<SCEV*>(Operands.begin(),
339 Operands.end())));
340}
341
342SCEVHandle SCEVAddRecExpr::
343replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
Dan Gohman89f85052007-10-22 18:31:58 +0000344 const SCEVHandle &Conc,
345 ScalarEvolution &SE) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000346 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
Dan Gohman89f85052007-10-22 18:31:58 +0000347 SCEVHandle H =
348 getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000349 if (H != getOperand(i)) {
350 std::vector<SCEVHandle> NewOps;
351 NewOps.reserve(getNumOperands());
352 for (unsigned j = 0; j != i; ++j)
353 NewOps.push_back(getOperand(j));
354 NewOps.push_back(H);
355 for (++i; i != e; ++i)
356 NewOps.push_back(getOperand(i)->
Dan Gohman89f85052007-10-22 18:31:58 +0000357 replaceSymbolicValuesWithConcrete(Sym, Conc, SE));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000358
Dan Gohman89f85052007-10-22 18:31:58 +0000359 return SE.getAddRecExpr(NewOps, L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000360 }
361 }
362 return this;
363}
364
365
366bool SCEVAddRecExpr::isLoopInvariant(const Loop *QueryLoop) const {
367 // This recurrence is invariant w.r.t to QueryLoop iff QueryLoop doesn't
368 // contain L and if the start is invariant.
369 return !QueryLoop->contains(L->getHeader()) &&
370 getOperand(0)->isLoopInvariant(QueryLoop);
371}
372
373
374void SCEVAddRecExpr::print(std::ostream &OS) const {
375 OS << "{" << *Operands[0];
376 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
377 OS << ",+," << *Operands[i];
378 OS << "}<" << L->getHeader()->getName() + ">";
379}
380
381// SCEVUnknowns - Only allow the creation of one SCEVUnknown for any particular
382// value. Don't use a SCEVHandle here, or else the object will never be
383// deleted!
384static ManagedStatic<std::map<Value*, SCEVUnknown*> > SCEVUnknowns;
385
386SCEVUnknown::~SCEVUnknown() { SCEVUnknowns->erase(V); }
387
388bool SCEVUnknown::isLoopInvariant(const Loop *L) const {
389 // All non-instruction values are loop invariant. All instructions are loop
390 // invariant if they are not contained in the specified loop.
391 if (Instruction *I = dyn_cast<Instruction>(V))
392 return !L->contains(I->getParent());
393 return true;
394}
395
396const Type *SCEVUnknown::getType() const {
397 return V->getType();
398}
399
400void SCEVUnknown::print(std::ostream &OS) const {
401 WriteAsOperand(OS, V, false);
402}
403
404//===----------------------------------------------------------------------===//
405// SCEV Utilities
406//===----------------------------------------------------------------------===//
407
408namespace {
409 /// SCEVComplexityCompare - Return true if the complexity of the LHS is less
410 /// than the complexity of the RHS. This comparator is used to canonicalize
411 /// expressions.
412 struct VISIBILITY_HIDDEN SCEVComplexityCompare {
Dan Gohmanc0c69cf2008-04-14 18:23:56 +0000413 bool operator()(const SCEV *LHS, const SCEV *RHS) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000414 return LHS->getSCEVType() < RHS->getSCEVType();
415 }
416 };
417}
418
419/// GroupByComplexity - Given a list of SCEV objects, order them by their
420/// complexity, and group objects of the same complexity together by value.
421/// When this routine is finished, we know that any duplicates in the vector are
422/// consecutive and that complexity is monotonically increasing.
423///
424/// Note that we go take special precautions to ensure that we get determinstic
425/// results from this routine. In other words, we don't want the results of
426/// this to depend on where the addresses of various SCEV objects happened to
427/// land in memory.
428///
429static void GroupByComplexity(std::vector<SCEVHandle> &Ops) {
430 if (Ops.size() < 2) return; // Noop
431 if (Ops.size() == 2) {
432 // This is the common case, which also happens to be trivially simple.
433 // Special case it.
Dan Gohmanc0c69cf2008-04-14 18:23:56 +0000434 if (SCEVComplexityCompare()(Ops[1], Ops[0]))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000435 std::swap(Ops[0], Ops[1]);
436 return;
437 }
438
439 // Do the rough sort by complexity.
440 std::sort(Ops.begin(), Ops.end(), SCEVComplexityCompare());
441
442 // Now that we are sorted by complexity, group elements of the same
443 // complexity. Note that this is, at worst, N^2, but the vector is likely to
444 // be extremely short in practice. Note that we take this approach because we
445 // do not want to depend on the addresses of the objects we are grouping.
446 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
447 SCEV *S = Ops[i];
448 unsigned Complexity = S->getSCEVType();
449
450 // If there are any objects of the same complexity and same value as this
451 // one, group them.
452 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
453 if (Ops[j] == S) { // Found a duplicate.
454 // Move it to immediately after i'th element.
455 std::swap(Ops[i+1], Ops[j]);
456 ++i; // no need to rescan it.
457 if (i == e-2) return; // Done!
458 }
459 }
460 }
461}
462
463
464
465//===----------------------------------------------------------------------===//
466// Simple SCEV method implementations
467//===----------------------------------------------------------------------===//
468
469/// getIntegerSCEV - Given an integer or FP type, create a constant for the
470/// specified signed integer value and return a SCEV for the constant.
Dan Gohman89f85052007-10-22 18:31:58 +0000471SCEVHandle ScalarEvolution::getIntegerSCEV(int Val, const Type *Ty) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000472 Constant *C;
473 if (Val == 0)
474 C = Constant::getNullValue(Ty);
475 else if (Ty->isFloatingPoint())
Chris Lattner5e0610f2008-04-20 00:41:09 +0000476 C = ConstantFP::get(APFloat(Ty==Type::FloatTy ? APFloat::IEEEsingle :
477 APFloat::IEEEdouble, Val));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000478 else
479 C = ConstantInt::get(Ty, Val);
Dan Gohman89f85052007-10-22 18:31:58 +0000480 return getUnknown(C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000481}
482
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000483/// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V
484///
Dan Gohman89f85052007-10-22 18:31:58 +0000485SCEVHandle ScalarEvolution::getNegativeSCEV(const SCEVHandle &V) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000486 if (SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
Dan Gohman89f85052007-10-22 18:31:58 +0000487 return getUnknown(ConstantExpr::getNeg(VC->getValue()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000488
Nick Lewycky0cf58682008-02-20 06:58:55 +0000489 return getMulExpr(V, getConstant(ConstantInt::getAllOnesValue(V->getType())));
Nick Lewyckye7a24ff2008-02-20 06:48:22 +0000490}
491
492/// getNotSCEV - Return a SCEV corresponding to ~V = -1-V
493SCEVHandle ScalarEvolution::getNotSCEV(const SCEVHandle &V) {
494 if (SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
495 return getUnknown(ConstantExpr::getNot(VC->getValue()));
496
Nick Lewycky0cf58682008-02-20 06:58:55 +0000497 SCEVHandle AllOnes = getConstant(ConstantInt::getAllOnesValue(V->getType()));
Nick Lewyckye7a24ff2008-02-20 06:48:22 +0000498 return getMinusSCEV(AllOnes, V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000499}
500
501/// getMinusSCEV - Return a SCEV corresponding to LHS - RHS.
502///
Dan Gohman89f85052007-10-22 18:31:58 +0000503SCEVHandle ScalarEvolution::getMinusSCEV(const SCEVHandle &LHS,
504 const SCEVHandle &RHS) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000505 // X - Y --> X + -Y
Dan Gohman89f85052007-10-22 18:31:58 +0000506 return getAddExpr(LHS, getNegativeSCEV(RHS));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000507}
508
509
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000510/// BinomialCoefficient - Compute BC(It, K). The result is of the same type as
511/// It. Assume, K > 0.
512static SCEVHandle BinomialCoefficient(SCEVHandle It, unsigned K,
513 ScalarEvolution &SE) {
514 // We are using the following formula for BC(It, K):
515 //
516 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
517 //
518 // Suppose, W is the bitwidth of It (and of the return value as well). We
519 // must be prepared for overflow. Hence, we must assure that the result of
520 // our computation is equal to the accurate one modulo 2^W. Unfortunately,
521 // division isn't safe in modular arithmetic. This means we must perform the
522 // whole computation accurately and then truncate the result to W bits.
523 //
524 // The dividend of the formula is a multiplication of K integers of bitwidth
525 // W. K*W bits suffice to compute it accurately.
526 //
527 // FIXME: We assume the divisor can be accurately computed using 16-bit
528 // unsigned integer type. It is true up to K = 8 (AddRecs of length 9). In
529 // future we may use APInt to use the minimum number of bits necessary to
530 // compute it accurately.
531 //
532 // It is safe to use unsigned division here: the dividend is nonnegative and
533 // the divisor is positive.
534
535 // Handle the simplest case efficiently.
536 if (K == 1)
537 return It;
538
539 assert(K < 9 && "We cannot handle such long AddRecs yet.");
540
541 // FIXME: A temporary hack to remove in future. Arbitrary precision integers
542 // aren't supported by the code generator yet. For the dividend, the bitwidth
543 // we use is the smallest power of 2 greater or equal to K*W and less or equal
544 // to 64. Note that setting the upper bound for bitwidth may still lead to
545 // miscompilation in some cases.
546 unsigned DividendBits = 1U << Log2_32_Ceil(K * It->getBitWidth());
547 if (DividendBits > 64)
548 DividendBits = 64;
549#if 0 // Waiting for the APInt support in the code generator...
550 unsigned DividendBits = K * It->getBitWidth();
551#endif
552
553 const IntegerType *DividendTy = IntegerType::get(DividendBits);
Nick Lewyckydbaa60a2008-06-13 04:38:55 +0000554 const SCEVHandle ExIt = SE.getTruncateOrZeroExtend(It, DividendTy);
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000555
556 // The final number of bits we need to perform the division is the maximum of
557 // dividend and divisor bitwidths.
558 const IntegerType *DivisionTy =
559 IntegerType::get(std::max(DividendBits, 16U));
560
561 // Compute K! We know K >= 2 here.
562 unsigned F = 2;
563 for (unsigned i = 3; i <= K; ++i)
564 F *= i;
565 APInt Divisor(DivisionTy->getBitWidth(), F);
566
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000567 // Handle this case efficiently, it is common to have constant iteration
568 // counts while computing loop exit values.
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000569 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(ExIt)) {
570 const APInt& N = SC->getValue()->getValue();
571 APInt Dividend(N.getBitWidth(), 1);
572 for (; K; --K)
573 Dividend *= N-(K-1);
574 if (DividendTy != DivisionTy)
575 Dividend = Dividend.zext(DivisionTy->getBitWidth());
Nick Lewyckydbaa60a2008-06-13 04:38:55 +0000576
577 APInt Result = Dividend.udiv(Divisor);
578 if (Result.getBitWidth() != It->getBitWidth())
579 Result = Result.trunc(It->getBitWidth());
580
581 return SE.getConstant(Result);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000582 }
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000583
584 SCEVHandle Dividend = ExIt;
585 for (unsigned i = 1; i != K; ++i)
586 Dividend =
587 SE.getMulExpr(Dividend,
588 SE.getMinusSCEV(ExIt, SE.getIntegerSCEV(i, DividendTy)));
Nick Lewyckydbaa60a2008-06-13 04:38:55 +0000589
590 return SE.getTruncateOrZeroExtend(
591 SE.getUDivExpr(
592 SE.getTruncateOrZeroExtend(Dividend, DivisionTy),
593 SE.getConstant(Divisor)
594 ), It->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000595}
596
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000597/// evaluateAtIteration - Return the value of this chain of recurrences at
598/// the specified iteration number. We can evaluate this recurrence by
599/// multiplying each element in the chain by the binomial coefficient
600/// corresponding to it. In other words, we can evaluate {A,+,B,+,C,+,D} as:
601///
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000602/// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000603///
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000604/// where BC(It, k) stands for binomial coefficient.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000605///
Dan Gohman89f85052007-10-22 18:31:58 +0000606SCEVHandle SCEVAddRecExpr::evaluateAtIteration(SCEVHandle It,
607 ScalarEvolution &SE) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000608 SCEVHandle Result = getStart();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000609 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000610 // The computation is correct in the face of overflow provided that the
611 // multiplication is performed _after_ the evaluation of the binomial
612 // coefficient.
613 SCEVHandle Val = SE.getMulExpr(getOperand(i),
614 BinomialCoefficient(It, i, SE));
Dan Gohman89f85052007-10-22 18:31:58 +0000615 Result = SE.getAddExpr(Result, Val);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000616 }
617 return Result;
618}
619
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000620//===----------------------------------------------------------------------===//
621// SCEV Expression folder implementations
622//===----------------------------------------------------------------------===//
623
Dan Gohman89f85052007-10-22 18:31:58 +0000624SCEVHandle ScalarEvolution::getTruncateExpr(const SCEVHandle &Op, const Type *Ty) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000625 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
Dan Gohman89f85052007-10-22 18:31:58 +0000626 return getUnknown(
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000627 ConstantExpr::getTrunc(SC->getValue(), Ty));
628
629 // If the input value is a chrec scev made out of constants, truncate
630 // all of the constants.
631 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
632 std::vector<SCEVHandle> Operands;
633 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
634 // FIXME: This should allow truncation of other expression types!
635 if (isa<SCEVConstant>(AddRec->getOperand(i)))
Dan Gohman89f85052007-10-22 18:31:58 +0000636 Operands.push_back(getTruncateExpr(AddRec->getOperand(i), Ty));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000637 else
638 break;
639 if (Operands.size() == AddRec->getNumOperands())
Dan Gohman89f85052007-10-22 18:31:58 +0000640 return getAddRecExpr(Operands, AddRec->getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000641 }
642
643 SCEVTruncateExpr *&Result = (*SCEVTruncates)[std::make_pair(Op, Ty)];
644 if (Result == 0) Result = new SCEVTruncateExpr(Op, Ty);
645 return Result;
646}
647
Dan Gohman89f85052007-10-22 18:31:58 +0000648SCEVHandle ScalarEvolution::getZeroExtendExpr(const SCEVHandle &Op, const Type *Ty) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000649 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
Dan Gohman89f85052007-10-22 18:31:58 +0000650 return getUnknown(
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000651 ConstantExpr::getZExt(SC->getValue(), Ty));
652
653 // FIXME: If the input value is a chrec scev, and we can prove that the value
654 // did not overflow the old, smaller, value, we can zero extend all of the
655 // operands (often constants). This would allow analysis of something like
656 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
657
658 SCEVZeroExtendExpr *&Result = (*SCEVZeroExtends)[std::make_pair(Op, Ty)];
659 if (Result == 0) Result = new SCEVZeroExtendExpr(Op, Ty);
660 return Result;
661}
662
Dan Gohman89f85052007-10-22 18:31:58 +0000663SCEVHandle ScalarEvolution::getSignExtendExpr(const SCEVHandle &Op, const Type *Ty) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000664 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
Dan Gohman89f85052007-10-22 18:31:58 +0000665 return getUnknown(
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000666 ConstantExpr::getSExt(SC->getValue(), Ty));
667
668 // FIXME: If the input value is a chrec scev, and we can prove that the value
669 // did not overflow the old, smaller, value, we can sign extend all of the
670 // operands (often constants). This would allow analysis of something like
671 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; }
672
673 SCEVSignExtendExpr *&Result = (*SCEVSignExtends)[std::make_pair(Op, Ty)];
674 if (Result == 0) Result = new SCEVSignExtendExpr(Op, Ty);
675 return Result;
676}
677
Nick Lewyckydbaa60a2008-06-13 04:38:55 +0000678/// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion
679/// of the input value to the specified type. If the type must be
680/// extended, it is zero extended.
681SCEVHandle ScalarEvolution::getTruncateOrZeroExtend(const SCEVHandle &V,
682 const Type *Ty) {
683 const Type *SrcTy = V->getType();
684 assert(SrcTy->isInteger() && Ty->isInteger() &&
685 "Cannot truncate or zero extend with non-integer arguments!");
686 if (SrcTy->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
687 return V; // No conversion
688 if (SrcTy->getPrimitiveSizeInBits() > Ty->getPrimitiveSizeInBits())
689 return getTruncateExpr(V, Ty);
690 return getZeroExtendExpr(V, Ty);
691}
692
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000693// get - Get a canonical add expression, or something simpler if possible.
Dan Gohman89f85052007-10-22 18:31:58 +0000694SCEVHandle ScalarEvolution::getAddExpr(std::vector<SCEVHandle> &Ops) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000695 assert(!Ops.empty() && "Cannot get empty add!");
696 if (Ops.size() == 1) return Ops[0];
697
698 // Sort by complexity, this groups all similar expression types together.
699 GroupByComplexity(Ops);
700
701 // If there are any constants, fold them together.
702 unsigned Idx = 0;
703 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
704 ++Idx;
705 assert(Idx < Ops.size());
706 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
707 // We found two constants, fold them together!
Nick Lewyckye7a24ff2008-02-20 06:48:22 +0000708 ConstantInt *Fold = ConstantInt::get(LHSC->getValue()->getValue() +
709 RHSC->getValue()->getValue());
710 Ops[0] = getConstant(Fold);
711 Ops.erase(Ops.begin()+1); // Erase the folded element
712 if (Ops.size() == 1) return Ops[0];
713 LHSC = cast<SCEVConstant>(Ops[0]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000714 }
715
716 // If we are left with a constant zero being added, strip it off.
717 if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
718 Ops.erase(Ops.begin());
719 --Idx;
720 }
721 }
722
723 if (Ops.size() == 1) return Ops[0];
724
725 // Okay, check to see if the same value occurs in the operand list twice. If
726 // so, merge them together into an multiply expression. Since we sorted the
727 // list, these values are required to be adjacent.
728 const Type *Ty = Ops[0]->getType();
729 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
730 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
731 // Found a match, merge the two values into a multiply, and add any
732 // remaining values to the result.
Dan Gohman89f85052007-10-22 18:31:58 +0000733 SCEVHandle Two = getIntegerSCEV(2, Ty);
734 SCEVHandle Mul = getMulExpr(Ops[i], Two);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000735 if (Ops.size() == 2)
736 return Mul;
737 Ops.erase(Ops.begin()+i, Ops.begin()+i+2);
738 Ops.push_back(Mul);
Dan Gohman89f85052007-10-22 18:31:58 +0000739 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000740 }
741
742 // Now we know the first non-constant operand. Skip past any cast SCEVs.
743 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
744 ++Idx;
745
746 // If there are add operands they would be next.
747 if (Idx < Ops.size()) {
748 bool DeletedAdd = false;
749 while (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
750 // If we have an add, expand the add operands onto the end of the operands
751 // list.
752 Ops.insert(Ops.end(), Add->op_begin(), Add->op_end());
753 Ops.erase(Ops.begin()+Idx);
754 DeletedAdd = true;
755 }
756
757 // If we deleted at least one add, we added operands to the end of the list,
758 // and they are not necessarily sorted. Recurse to resort and resimplify
759 // any operands we just aquired.
760 if (DeletedAdd)
Dan Gohman89f85052007-10-22 18:31:58 +0000761 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000762 }
763
764 // Skip over the add expression until we get to a multiply.
765 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
766 ++Idx;
767
768 // If we are adding something to a multiply expression, make sure the
769 // something is not already an operand of the multiply. If so, merge it into
770 // the multiply.
771 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
772 SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
773 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
774 SCEV *MulOpSCEV = Mul->getOperand(MulOp);
775 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
776 if (MulOpSCEV == Ops[AddOp] && !isa<SCEVConstant>(MulOpSCEV)) {
777 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
778 SCEVHandle InnerMul = Mul->getOperand(MulOp == 0);
779 if (Mul->getNumOperands() != 2) {
780 // If the multiply has more than two operands, we must get the
781 // Y*Z term.
782 std::vector<SCEVHandle> MulOps(Mul->op_begin(), Mul->op_end());
783 MulOps.erase(MulOps.begin()+MulOp);
Dan Gohman89f85052007-10-22 18:31:58 +0000784 InnerMul = getMulExpr(MulOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000785 }
Dan Gohman89f85052007-10-22 18:31:58 +0000786 SCEVHandle One = getIntegerSCEV(1, Ty);
787 SCEVHandle AddOne = getAddExpr(InnerMul, One);
788 SCEVHandle OuterMul = getMulExpr(AddOne, Ops[AddOp]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000789 if (Ops.size() == 2) return OuterMul;
790 if (AddOp < Idx) {
791 Ops.erase(Ops.begin()+AddOp);
792 Ops.erase(Ops.begin()+Idx-1);
793 } else {
794 Ops.erase(Ops.begin()+Idx);
795 Ops.erase(Ops.begin()+AddOp-1);
796 }
797 Ops.push_back(OuterMul);
Dan Gohman89f85052007-10-22 18:31:58 +0000798 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000799 }
800
801 // Check this multiply against other multiplies being added together.
802 for (unsigned OtherMulIdx = Idx+1;
803 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
804 ++OtherMulIdx) {
805 SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
806 // If MulOp occurs in OtherMul, we can fold the two multiplies
807 // together.
808 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
809 OMulOp != e; ++OMulOp)
810 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
811 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
812 SCEVHandle InnerMul1 = Mul->getOperand(MulOp == 0);
813 if (Mul->getNumOperands() != 2) {
814 std::vector<SCEVHandle> MulOps(Mul->op_begin(), Mul->op_end());
815 MulOps.erase(MulOps.begin()+MulOp);
Dan Gohman89f85052007-10-22 18:31:58 +0000816 InnerMul1 = getMulExpr(MulOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000817 }
818 SCEVHandle InnerMul2 = OtherMul->getOperand(OMulOp == 0);
819 if (OtherMul->getNumOperands() != 2) {
820 std::vector<SCEVHandle> MulOps(OtherMul->op_begin(),
821 OtherMul->op_end());
822 MulOps.erase(MulOps.begin()+OMulOp);
Dan Gohman89f85052007-10-22 18:31:58 +0000823 InnerMul2 = getMulExpr(MulOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000824 }
Dan Gohman89f85052007-10-22 18:31:58 +0000825 SCEVHandle InnerMulSum = getAddExpr(InnerMul1,InnerMul2);
826 SCEVHandle OuterMul = getMulExpr(MulOpSCEV, InnerMulSum);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000827 if (Ops.size() == 2) return OuterMul;
828 Ops.erase(Ops.begin()+Idx);
829 Ops.erase(Ops.begin()+OtherMulIdx-1);
830 Ops.push_back(OuterMul);
Dan Gohman89f85052007-10-22 18:31:58 +0000831 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000832 }
833 }
834 }
835 }
836
837 // If there are any add recurrences in the operands list, see if any other
838 // added values are loop invariant. If so, we can fold them into the
839 // recurrence.
840 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
841 ++Idx;
842
843 // Scan over all recurrences, trying to fold loop invariants into them.
844 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
845 // Scan all of the other operands to this add and add them to the vector if
846 // they are loop invariant w.r.t. the recurrence.
847 std::vector<SCEVHandle> LIOps;
848 SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
849 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
850 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
851 LIOps.push_back(Ops[i]);
852 Ops.erase(Ops.begin()+i);
853 --i; --e;
854 }
855
856 // If we found some loop invariants, fold them into the recurrence.
857 if (!LIOps.empty()) {
858 // NLI + LI + { Start,+,Step} --> NLI + { LI+Start,+,Step }
859 LIOps.push_back(AddRec->getStart());
860
861 std::vector<SCEVHandle> AddRecOps(AddRec->op_begin(), AddRec->op_end());
Dan Gohman89f85052007-10-22 18:31:58 +0000862 AddRecOps[0] = getAddExpr(LIOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000863
Dan Gohman89f85052007-10-22 18:31:58 +0000864 SCEVHandle NewRec = getAddRecExpr(AddRecOps, AddRec->getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000865 // If all of the other operands were loop invariant, we are done.
866 if (Ops.size() == 1) return NewRec;
867
868 // Otherwise, add the folded AddRec by the non-liv parts.
869 for (unsigned i = 0;; ++i)
870 if (Ops[i] == AddRec) {
871 Ops[i] = NewRec;
872 break;
873 }
Dan Gohman89f85052007-10-22 18:31:58 +0000874 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000875 }
876
877 // Okay, if there weren't any loop invariants to be folded, check to see if
878 // there are multiple AddRec's with the same loop induction variable being
879 // added together. If so, we can fold them.
880 for (unsigned OtherIdx = Idx+1;
881 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
882 if (OtherIdx != Idx) {
883 SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
884 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
885 // Other + {A,+,B} + {C,+,D} --> Other + {A+C,+,B+D}
886 std::vector<SCEVHandle> NewOps(AddRec->op_begin(), AddRec->op_end());
887 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); i != e; ++i) {
888 if (i >= NewOps.size()) {
889 NewOps.insert(NewOps.end(), OtherAddRec->op_begin()+i,
890 OtherAddRec->op_end());
891 break;
892 }
Dan Gohman89f85052007-10-22 18:31:58 +0000893 NewOps[i] = getAddExpr(NewOps[i], OtherAddRec->getOperand(i));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000894 }
Dan Gohman89f85052007-10-22 18:31:58 +0000895 SCEVHandle NewAddRec = getAddRecExpr(NewOps, AddRec->getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000896
897 if (Ops.size() == 2) return NewAddRec;
898
899 Ops.erase(Ops.begin()+Idx);
900 Ops.erase(Ops.begin()+OtherIdx-1);
901 Ops.push_back(NewAddRec);
Dan Gohman89f85052007-10-22 18:31:58 +0000902 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000903 }
904 }
905
906 // Otherwise couldn't fold anything into this recurrence. Move onto the
907 // next one.
908 }
909
910 // Okay, it looks like we really DO need an add expr. Check to see if we
911 // already have one, otherwise create a new one.
912 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
913 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scAddExpr,
914 SCEVOps)];
915 if (Result == 0) Result = new SCEVAddExpr(Ops);
916 return Result;
917}
918
919
Dan Gohman89f85052007-10-22 18:31:58 +0000920SCEVHandle ScalarEvolution::getMulExpr(std::vector<SCEVHandle> &Ops) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000921 assert(!Ops.empty() && "Cannot get empty mul!");
922
923 // Sort by complexity, this groups all similar expression types together.
924 GroupByComplexity(Ops);
925
926 // If there are any constants, fold them together.
927 unsigned Idx = 0;
928 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
929
930 // C1*(C2+V) -> C1*C2 + C1*V
931 if (Ops.size() == 2)
932 if (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
933 if (Add->getNumOperands() == 2 &&
934 isa<SCEVConstant>(Add->getOperand(0)))
Dan Gohman89f85052007-10-22 18:31:58 +0000935 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0)),
936 getMulExpr(LHSC, Add->getOperand(1)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000937
938
939 ++Idx;
940 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
941 // We found two constants, fold them together!
Nick Lewyckye7a24ff2008-02-20 06:48:22 +0000942 ConstantInt *Fold = ConstantInt::get(LHSC->getValue()->getValue() *
943 RHSC->getValue()->getValue());
944 Ops[0] = getConstant(Fold);
945 Ops.erase(Ops.begin()+1); // Erase the folded element
946 if (Ops.size() == 1) return Ops[0];
947 LHSC = cast<SCEVConstant>(Ops[0]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000948 }
949
950 // If we are left with a constant one being multiplied, strip it off.
951 if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) {
952 Ops.erase(Ops.begin());
953 --Idx;
954 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
955 // If we have a multiply of zero, it will always be zero.
956 return Ops[0];
957 }
958 }
959
960 // Skip over the add expression until we get to a multiply.
961 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
962 ++Idx;
963
964 if (Ops.size() == 1)
965 return Ops[0];
966
967 // If there are mul operands inline them all into this expression.
968 if (Idx < Ops.size()) {
969 bool DeletedMul = false;
970 while (SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
971 // If we have an mul, expand the mul operands onto the end of the operands
972 // list.
973 Ops.insert(Ops.end(), Mul->op_begin(), Mul->op_end());
974 Ops.erase(Ops.begin()+Idx);
975 DeletedMul = true;
976 }
977
978 // If we deleted at least one mul, we added operands to the end of the list,
979 // and they are not necessarily sorted. Recurse to resort and resimplify
980 // any operands we just aquired.
981 if (DeletedMul)
Dan Gohman89f85052007-10-22 18:31:58 +0000982 return getMulExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000983 }
984
985 // If there are any add recurrences in the operands list, see if any other
986 // added values are loop invariant. If so, we can fold them into the
987 // recurrence.
988 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
989 ++Idx;
990
991 // Scan over all recurrences, trying to fold loop invariants into them.
992 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
993 // Scan all of the other operands to this mul and add them to the vector if
994 // they are loop invariant w.r.t. the recurrence.
995 std::vector<SCEVHandle> LIOps;
996 SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
997 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
998 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
999 LIOps.push_back(Ops[i]);
1000 Ops.erase(Ops.begin()+i);
1001 --i; --e;
1002 }
1003
1004 // If we found some loop invariants, fold them into the recurrence.
1005 if (!LIOps.empty()) {
1006 // NLI * LI * { Start,+,Step} --> NLI * { LI*Start,+,LI*Step }
1007 std::vector<SCEVHandle> NewOps;
1008 NewOps.reserve(AddRec->getNumOperands());
1009 if (LIOps.size() == 1) {
1010 SCEV *Scale = LIOps[0];
1011 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
Dan Gohman89f85052007-10-22 18:31:58 +00001012 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001013 } else {
1014 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
1015 std::vector<SCEVHandle> MulOps(LIOps);
1016 MulOps.push_back(AddRec->getOperand(i));
Dan Gohman89f85052007-10-22 18:31:58 +00001017 NewOps.push_back(getMulExpr(MulOps));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001018 }
1019 }
1020
Dan Gohman89f85052007-10-22 18:31:58 +00001021 SCEVHandle NewRec = getAddRecExpr(NewOps, AddRec->getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001022
1023 // If all of the other operands were loop invariant, we are done.
1024 if (Ops.size() == 1) return NewRec;
1025
1026 // Otherwise, multiply the folded AddRec by the non-liv parts.
1027 for (unsigned i = 0;; ++i)
1028 if (Ops[i] == AddRec) {
1029 Ops[i] = NewRec;
1030 break;
1031 }
Dan Gohman89f85052007-10-22 18:31:58 +00001032 return getMulExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001033 }
1034
1035 // Okay, if there weren't any loop invariants to be folded, check to see if
1036 // there are multiple AddRec's with the same loop induction variable being
1037 // multiplied together. If so, we can fold them.
1038 for (unsigned OtherIdx = Idx+1;
1039 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
1040 if (OtherIdx != Idx) {
1041 SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
1042 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
1043 // F * G --> {A,+,B} * {C,+,D} --> {A*C,+,F*D + G*B + B*D}
1044 SCEVAddRecExpr *F = AddRec, *G = OtherAddRec;
Dan Gohman89f85052007-10-22 18:31:58 +00001045 SCEVHandle NewStart = getMulExpr(F->getStart(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001046 G->getStart());
Dan Gohman89f85052007-10-22 18:31:58 +00001047 SCEVHandle B = F->getStepRecurrence(*this);
1048 SCEVHandle D = G->getStepRecurrence(*this);
1049 SCEVHandle NewStep = getAddExpr(getMulExpr(F, D),
1050 getMulExpr(G, B),
1051 getMulExpr(B, D));
1052 SCEVHandle NewAddRec = getAddRecExpr(NewStart, NewStep,
1053 F->getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001054 if (Ops.size() == 2) return NewAddRec;
1055
1056 Ops.erase(Ops.begin()+Idx);
1057 Ops.erase(Ops.begin()+OtherIdx-1);
1058 Ops.push_back(NewAddRec);
Dan Gohman89f85052007-10-22 18:31:58 +00001059 return getMulExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001060 }
1061 }
1062
1063 // Otherwise couldn't fold anything into this recurrence. Move onto the
1064 // next one.
1065 }
1066
1067 // Okay, it looks like we really DO need an mul expr. Check to see if we
1068 // already have one, otherwise create a new one.
1069 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
1070 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scMulExpr,
1071 SCEVOps)];
1072 if (Result == 0)
1073 Result = new SCEVMulExpr(Ops);
1074 return Result;
1075}
1076
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +00001077SCEVHandle ScalarEvolution::getUDivExpr(const SCEVHandle &LHS, const SCEVHandle &RHS) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001078 if (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
1079 if (RHSC->getValue()->equalsInt(1))
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +00001080 return LHS; // X udiv 1 --> x
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001081
1082 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
1083 Constant *LHSCV = LHSC->getValue();
1084 Constant *RHSCV = RHSC->getValue();
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +00001085 return getUnknown(ConstantExpr::getUDiv(LHSCV, RHSCV));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001086 }
1087 }
1088
1089 // FIXME: implement folding of (X*4)/4 when we know X*4 doesn't overflow.
1090
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +00001091 SCEVUDivExpr *&Result = (*SCEVUDivs)[std::make_pair(LHS, RHS)];
1092 if (Result == 0) Result = new SCEVUDivExpr(LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001093 return Result;
1094}
1095
1096
1097/// SCEVAddRecExpr::get - Get a add recurrence expression for the
1098/// specified loop. Simplify the expression as much as possible.
Dan Gohman89f85052007-10-22 18:31:58 +00001099SCEVHandle ScalarEvolution::getAddRecExpr(const SCEVHandle &Start,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001100 const SCEVHandle &Step, const Loop *L) {
1101 std::vector<SCEVHandle> Operands;
1102 Operands.push_back(Start);
1103 if (SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
1104 if (StepChrec->getLoop() == L) {
1105 Operands.insert(Operands.end(), StepChrec->op_begin(),
1106 StepChrec->op_end());
Dan Gohman89f85052007-10-22 18:31:58 +00001107 return getAddRecExpr(Operands, L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001108 }
1109
1110 Operands.push_back(Step);
Dan Gohman89f85052007-10-22 18:31:58 +00001111 return getAddRecExpr(Operands, L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001112}
1113
1114/// SCEVAddRecExpr::get - Get a add recurrence expression for the
1115/// specified loop. Simplify the expression as much as possible.
Dan Gohman89f85052007-10-22 18:31:58 +00001116SCEVHandle ScalarEvolution::getAddRecExpr(std::vector<SCEVHandle> &Operands,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001117 const Loop *L) {
1118 if (Operands.size() == 1) return Operands[0];
1119
Dan Gohman7b560c42008-06-18 16:23:07 +00001120 if (Operands.back()->isZero()) {
1121 Operands.pop_back();
1122 return getAddRecExpr(Operands, L); // { X,+,0 } --> X
1123 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001124
1125 SCEVAddRecExpr *&Result =
1126 (*SCEVAddRecExprs)[std::make_pair(L, std::vector<SCEV*>(Operands.begin(),
1127 Operands.end()))];
1128 if (Result == 0) Result = new SCEVAddRecExpr(Operands, L);
1129 return Result;
1130}
1131
Nick Lewycky711640a2007-11-25 22:41:31 +00001132SCEVHandle ScalarEvolution::getSMaxExpr(const SCEVHandle &LHS,
1133 const SCEVHandle &RHS) {
1134 std::vector<SCEVHandle> Ops;
1135 Ops.push_back(LHS);
1136 Ops.push_back(RHS);
1137 return getSMaxExpr(Ops);
1138}
1139
1140SCEVHandle ScalarEvolution::getSMaxExpr(std::vector<SCEVHandle> Ops) {
1141 assert(!Ops.empty() && "Cannot get empty smax!");
1142 if (Ops.size() == 1) return Ops[0];
1143
1144 // Sort by complexity, this groups all similar expression types together.
1145 GroupByComplexity(Ops);
1146
1147 // If there are any constants, fold them together.
1148 unsigned Idx = 0;
1149 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
1150 ++Idx;
1151 assert(Idx < Ops.size());
1152 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
1153 // We found two constants, fold them together!
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001154 ConstantInt *Fold = ConstantInt::get(
Nick Lewycky711640a2007-11-25 22:41:31 +00001155 APIntOps::smax(LHSC->getValue()->getValue(),
1156 RHSC->getValue()->getValue()));
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001157 Ops[0] = getConstant(Fold);
1158 Ops.erase(Ops.begin()+1); // Erase the folded element
1159 if (Ops.size() == 1) return Ops[0];
1160 LHSC = cast<SCEVConstant>(Ops[0]);
Nick Lewycky711640a2007-11-25 22:41:31 +00001161 }
1162
1163 // If we are left with a constant -inf, strip it off.
1164 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) {
1165 Ops.erase(Ops.begin());
1166 --Idx;
1167 }
1168 }
1169
1170 if (Ops.size() == 1) return Ops[0];
1171
1172 // Find the first SMax
1173 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr)
1174 ++Idx;
1175
1176 // Check to see if one of the operands is an SMax. If so, expand its operands
1177 // onto our operand list, and recurse to simplify.
1178 if (Idx < Ops.size()) {
1179 bool DeletedSMax = false;
1180 while (SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) {
1181 Ops.insert(Ops.end(), SMax->op_begin(), SMax->op_end());
1182 Ops.erase(Ops.begin()+Idx);
1183 DeletedSMax = true;
1184 }
1185
1186 if (DeletedSMax)
1187 return getSMaxExpr(Ops);
1188 }
1189
1190 // Okay, check to see if the same value occurs in the operand list twice. If
1191 // so, delete one. Since we sorted the list, these values are required to
1192 // be adjacent.
1193 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1194 if (Ops[i] == Ops[i+1]) { // X smax Y smax Y --> X smax Y
1195 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
1196 --i; --e;
1197 }
1198
1199 if (Ops.size() == 1) return Ops[0];
1200
1201 assert(!Ops.empty() && "Reduced smax down to nothing!");
1202
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001203 // Okay, it looks like we really DO need an smax expr. Check to see if we
Nick Lewycky711640a2007-11-25 22:41:31 +00001204 // already have one, otherwise create a new one.
1205 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
1206 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scSMaxExpr,
1207 SCEVOps)];
1208 if (Result == 0) Result = new SCEVSMaxExpr(Ops);
1209 return Result;
1210}
1211
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001212SCEVHandle ScalarEvolution::getUMaxExpr(const SCEVHandle &LHS,
1213 const SCEVHandle &RHS) {
1214 std::vector<SCEVHandle> Ops;
1215 Ops.push_back(LHS);
1216 Ops.push_back(RHS);
1217 return getUMaxExpr(Ops);
1218}
1219
1220SCEVHandle ScalarEvolution::getUMaxExpr(std::vector<SCEVHandle> Ops) {
1221 assert(!Ops.empty() && "Cannot get empty umax!");
1222 if (Ops.size() == 1) return Ops[0];
1223
1224 // Sort by complexity, this groups all similar expression types together.
1225 GroupByComplexity(Ops);
1226
1227 // If there are any constants, fold them together.
1228 unsigned Idx = 0;
1229 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
1230 ++Idx;
1231 assert(Idx < Ops.size());
1232 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
1233 // We found two constants, fold them together!
1234 ConstantInt *Fold = ConstantInt::get(
1235 APIntOps::umax(LHSC->getValue()->getValue(),
1236 RHSC->getValue()->getValue()));
1237 Ops[0] = getConstant(Fold);
1238 Ops.erase(Ops.begin()+1); // Erase the folded element
1239 if (Ops.size() == 1) return Ops[0];
1240 LHSC = cast<SCEVConstant>(Ops[0]);
1241 }
1242
1243 // If we are left with a constant zero, strip it off.
1244 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) {
1245 Ops.erase(Ops.begin());
1246 --Idx;
1247 }
1248 }
1249
1250 if (Ops.size() == 1) return Ops[0];
1251
1252 // Find the first UMax
1253 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr)
1254 ++Idx;
1255
1256 // Check to see if one of the operands is a UMax. If so, expand its operands
1257 // onto our operand list, and recurse to simplify.
1258 if (Idx < Ops.size()) {
1259 bool DeletedUMax = false;
1260 while (SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) {
1261 Ops.insert(Ops.end(), UMax->op_begin(), UMax->op_end());
1262 Ops.erase(Ops.begin()+Idx);
1263 DeletedUMax = true;
1264 }
1265
1266 if (DeletedUMax)
1267 return getUMaxExpr(Ops);
1268 }
1269
1270 // Okay, check to see if the same value occurs in the operand list twice. If
1271 // so, delete one. Since we sorted the list, these values are required to
1272 // be adjacent.
1273 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1274 if (Ops[i] == Ops[i+1]) { // X umax Y umax Y --> X umax Y
1275 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
1276 --i; --e;
1277 }
1278
1279 if (Ops.size() == 1) return Ops[0];
1280
1281 assert(!Ops.empty() && "Reduced umax down to nothing!");
1282
1283 // Okay, it looks like we really DO need a umax expr. Check to see if we
1284 // already have one, otherwise create a new one.
1285 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
1286 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scUMaxExpr,
1287 SCEVOps)];
1288 if (Result == 0) Result = new SCEVUMaxExpr(Ops);
1289 return Result;
1290}
1291
Dan Gohman89f85052007-10-22 18:31:58 +00001292SCEVHandle ScalarEvolution::getUnknown(Value *V) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001293 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
Dan Gohman89f85052007-10-22 18:31:58 +00001294 return getConstant(CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001295 SCEVUnknown *&Result = (*SCEVUnknowns)[V];
1296 if (Result == 0) Result = new SCEVUnknown(V);
1297 return Result;
1298}
1299
1300
1301//===----------------------------------------------------------------------===//
1302// ScalarEvolutionsImpl Definition and Implementation
1303//===----------------------------------------------------------------------===//
1304//
1305/// ScalarEvolutionsImpl - This class implements the main driver for the scalar
1306/// evolution code.
1307///
1308namespace {
1309 struct VISIBILITY_HIDDEN ScalarEvolutionsImpl {
Dan Gohman89f85052007-10-22 18:31:58 +00001310 /// SE - A reference to the public ScalarEvolution object.
1311 ScalarEvolution &SE;
1312
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001313 /// F - The function we are analyzing.
1314 ///
1315 Function &F;
1316
1317 /// LI - The loop information for the function we are currently analyzing.
1318 ///
1319 LoopInfo &LI;
1320
1321 /// UnknownValue - This SCEV is used to represent unknown trip counts and
1322 /// things.
1323 SCEVHandle UnknownValue;
1324
1325 /// Scalars - This is a cache of the scalars we have analyzed so far.
1326 ///
1327 std::map<Value*, SCEVHandle> Scalars;
1328
1329 /// IterationCounts - Cache the iteration count of the loops for this
1330 /// function as they are computed.
1331 std::map<const Loop*, SCEVHandle> IterationCounts;
1332
1333 /// ConstantEvolutionLoopExitValue - This map contains entries for all of
1334 /// the PHI instructions that we attempt to compute constant evolutions for.
1335 /// This allows us to avoid potentially expensive recomputation of these
1336 /// properties. An instruction maps to null if we are unable to compute its
1337 /// exit value.
1338 std::map<PHINode*, Constant*> ConstantEvolutionLoopExitValue;
1339
1340 public:
Dan Gohman89f85052007-10-22 18:31:58 +00001341 ScalarEvolutionsImpl(ScalarEvolution &se, Function &f, LoopInfo &li)
1342 : SE(se), F(f), LI(li), UnknownValue(new SCEVCouldNotCompute()) {}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001343
1344 /// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
1345 /// expression and create a new one.
1346 SCEVHandle getSCEV(Value *V);
1347
1348 /// hasSCEV - Return true if the SCEV for this value has already been
1349 /// computed.
1350 bool hasSCEV(Value *V) const {
1351 return Scalars.count(V);
1352 }
1353
1354 /// setSCEV - Insert the specified SCEV into the map of current SCEVs for
1355 /// the specified value.
1356 void setSCEV(Value *V, const SCEVHandle &H) {
1357 bool isNew = Scalars.insert(std::make_pair(V, H)).second;
1358 assert(isNew && "This entry already existed!");
1359 }
1360
1361
1362 /// getSCEVAtScope - Compute the value of the specified expression within
1363 /// the indicated loop (which may be null to indicate in no loop). If the
1364 /// expression cannot be evaluated, return UnknownValue itself.
1365 SCEVHandle getSCEVAtScope(SCEV *V, const Loop *L);
1366
1367
1368 /// hasLoopInvariantIterationCount - Return true if the specified loop has
1369 /// an analyzable loop-invariant iteration count.
1370 bool hasLoopInvariantIterationCount(const Loop *L);
1371
1372 /// getIterationCount - If the specified loop has a predictable iteration
1373 /// count, return it. Note that it is not valid to call this method on a
1374 /// loop without a loop-invariant iteration count.
1375 SCEVHandle getIterationCount(const Loop *L);
1376
1377 /// deleteValueFromRecords - This method should be called by the
1378 /// client before it removes a value from the program, to make sure
1379 /// that no dangling references are left around.
1380 void deleteValueFromRecords(Value *V);
1381
1382 private:
1383 /// createSCEV - We know that there is no SCEV for the specified value.
1384 /// Analyze the expression.
1385 SCEVHandle createSCEV(Value *V);
1386
1387 /// createNodeForPHI - Provide the special handling we need to analyze PHI
1388 /// SCEVs.
1389 SCEVHandle createNodeForPHI(PHINode *PN);
1390
1391 /// ReplaceSymbolicValueWithConcrete - This looks up the computed SCEV value
1392 /// for the specified instruction and replaces any references to the
1393 /// symbolic value SymName with the specified value. This is used during
1394 /// PHI resolution.
1395 void ReplaceSymbolicValueWithConcrete(Instruction *I,
1396 const SCEVHandle &SymName,
1397 const SCEVHandle &NewVal);
1398
1399 /// ComputeIterationCount - Compute the number of times the specified loop
1400 /// will iterate.
1401 SCEVHandle ComputeIterationCount(const Loop *L);
1402
1403 /// ComputeLoadConstantCompareIterationCount - Given an exit condition of
Nick Lewycky3a8a41f2007-11-20 08:44:50 +00001404 /// 'icmp op load X, cst', try to see if we can compute the trip count.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001405 SCEVHandle ComputeLoadConstantCompareIterationCount(LoadInst *LI,
1406 Constant *RHS,
1407 const Loop *L,
1408 ICmpInst::Predicate p);
1409
1410 /// ComputeIterationCountExhaustively - If the trip is known to execute a
1411 /// constant number of times (the condition evolves only from constants),
1412 /// try to evaluate a few iterations of the loop until we get the exit
1413 /// condition gets a value of ExitWhen (true or false). If we cannot
1414 /// evaluate the trip count of the loop, return UnknownValue.
1415 SCEVHandle ComputeIterationCountExhaustively(const Loop *L, Value *Cond,
1416 bool ExitWhen);
1417
1418 /// HowFarToZero - Return the number of times a backedge comparing the
1419 /// specified value to zero will execute. If not computable, return
1420 /// UnknownValue.
1421 SCEVHandle HowFarToZero(SCEV *V, const Loop *L);
1422
1423 /// HowFarToNonZero - Return the number of times a backedge checking the
1424 /// specified value for nonzero will execute. If not computable, return
1425 /// UnknownValue.
1426 SCEVHandle HowFarToNonZero(SCEV *V, const Loop *L);
1427
1428 /// HowManyLessThans - Return the number of times a backedge containing the
1429 /// specified less-than comparison will execute. If not computable, return
Nick Lewyckyb7c28942007-08-06 19:21:00 +00001430 /// UnknownValue. isSigned specifies whether the less-than is signed.
1431 SCEVHandle HowManyLessThans(SCEV *LHS, SCEV *RHS, const Loop *L,
1432 bool isSigned);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001433
1434 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
1435 /// in the header of its containing loop, we know the loop executes a
1436 /// constant number of times, and the PHI node is just a recurrence
1437 /// involving constants, fold it.
1438 Constant *getConstantEvolutionLoopExitValue(PHINode *PN, const APInt& Its,
1439 const Loop *L);
1440 };
1441}
1442
1443//===----------------------------------------------------------------------===//
1444// Basic SCEV Analysis and PHI Idiom Recognition Code
1445//
1446
1447/// deleteValueFromRecords - This method should be called by the
1448/// client before it removes an instruction from the program, to make sure
1449/// that no dangling references are left around.
1450void ScalarEvolutionsImpl::deleteValueFromRecords(Value *V) {
1451 SmallVector<Value *, 16> Worklist;
1452
1453 if (Scalars.erase(V)) {
1454 if (PHINode *PN = dyn_cast<PHINode>(V))
1455 ConstantEvolutionLoopExitValue.erase(PN);
1456 Worklist.push_back(V);
1457 }
1458
1459 while (!Worklist.empty()) {
1460 Value *VV = Worklist.back();
1461 Worklist.pop_back();
1462
1463 for (Instruction::use_iterator UI = VV->use_begin(), UE = VV->use_end();
1464 UI != UE; ++UI) {
1465 Instruction *Inst = cast<Instruction>(*UI);
1466 if (Scalars.erase(Inst)) {
1467 if (PHINode *PN = dyn_cast<PHINode>(VV))
1468 ConstantEvolutionLoopExitValue.erase(PN);
1469 Worklist.push_back(Inst);
1470 }
1471 }
1472 }
1473}
1474
1475
1476/// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
1477/// expression and create a new one.
1478SCEVHandle ScalarEvolutionsImpl::getSCEV(Value *V) {
1479 assert(V->getType() != Type::VoidTy && "Can't analyze void expressions!");
1480
1481 std::map<Value*, SCEVHandle>::iterator I = Scalars.find(V);
1482 if (I != Scalars.end()) return I->second;
1483 SCEVHandle S = createSCEV(V);
1484 Scalars.insert(std::make_pair(V, S));
1485 return S;
1486}
1487
1488/// ReplaceSymbolicValueWithConcrete - This looks up the computed SCEV value for
1489/// the specified instruction and replaces any references to the symbolic value
1490/// SymName with the specified value. This is used during PHI resolution.
1491void ScalarEvolutionsImpl::
1492ReplaceSymbolicValueWithConcrete(Instruction *I, const SCEVHandle &SymName,
1493 const SCEVHandle &NewVal) {
1494 std::map<Value*, SCEVHandle>::iterator SI = Scalars.find(I);
1495 if (SI == Scalars.end()) return;
1496
1497 SCEVHandle NV =
Dan Gohman89f85052007-10-22 18:31:58 +00001498 SI->second->replaceSymbolicValuesWithConcrete(SymName, NewVal, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001499 if (NV == SI->second) return; // No change.
1500
1501 SI->second = NV; // Update the scalars map!
1502
1503 // Any instruction values that use this instruction might also need to be
1504 // updated!
1505 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1506 UI != E; ++UI)
1507 ReplaceSymbolicValueWithConcrete(cast<Instruction>(*UI), SymName, NewVal);
1508}
1509
1510/// createNodeForPHI - PHI nodes have two cases. Either the PHI node exists in
1511/// a loop header, making it a potential recurrence, or it doesn't.
1512///
1513SCEVHandle ScalarEvolutionsImpl::createNodeForPHI(PHINode *PN) {
1514 if (PN->getNumIncomingValues() == 2) // The loops have been canonicalized.
1515 if (const Loop *L = LI.getLoopFor(PN->getParent()))
1516 if (L->getHeader() == PN->getParent()) {
1517 // If it lives in the loop header, it has two incoming values, one
1518 // from outside the loop, and one from inside.
1519 unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0));
1520 unsigned BackEdge = IncomingEdge^1;
1521
1522 // While we are analyzing this PHI node, handle its value symbolically.
Dan Gohman89f85052007-10-22 18:31:58 +00001523 SCEVHandle SymbolicName = SE.getUnknown(PN);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001524 assert(Scalars.find(PN) == Scalars.end() &&
1525 "PHI node already processed?");
1526 Scalars.insert(std::make_pair(PN, SymbolicName));
1527
1528 // Using this symbolic name for the PHI, analyze the value coming around
1529 // the back-edge.
1530 SCEVHandle BEValue = getSCEV(PN->getIncomingValue(BackEdge));
1531
1532 // NOTE: If BEValue is loop invariant, we know that the PHI node just
1533 // has a special value for the first iteration of the loop.
1534
1535 // If the value coming around the backedge is an add with the symbolic
1536 // value we just inserted, then we found a simple induction variable!
1537 if (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
1538 // If there is a single occurrence of the symbolic value, replace it
1539 // with a recurrence.
1540 unsigned FoundIndex = Add->getNumOperands();
1541 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
1542 if (Add->getOperand(i) == SymbolicName)
1543 if (FoundIndex == e) {
1544 FoundIndex = i;
1545 break;
1546 }
1547
1548 if (FoundIndex != Add->getNumOperands()) {
1549 // Create an add with everything but the specified operand.
1550 std::vector<SCEVHandle> Ops;
1551 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
1552 if (i != FoundIndex)
1553 Ops.push_back(Add->getOperand(i));
Dan Gohman89f85052007-10-22 18:31:58 +00001554 SCEVHandle Accum = SE.getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001555
1556 // This is not a valid addrec if the step amount is varying each
1557 // loop iteration, but is not itself an addrec in this loop.
1558 if (Accum->isLoopInvariant(L) ||
1559 (isa<SCEVAddRecExpr>(Accum) &&
1560 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
1561 SCEVHandle StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
Dan Gohman89f85052007-10-22 18:31:58 +00001562 SCEVHandle PHISCEV = SE.getAddRecExpr(StartVal, Accum, L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001563
1564 // Okay, for the entire analysis of this edge we assumed the PHI
1565 // to be symbolic. We now need to go back and update all of the
1566 // entries for the scalars that use the PHI (except for the PHI
1567 // itself) to use the new analyzed value instead of the "symbolic"
1568 // value.
1569 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
1570 return PHISCEV;
1571 }
1572 }
1573 } else if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(BEValue)) {
1574 // Otherwise, this could be a loop like this:
1575 // i = 0; for (j = 1; ..; ++j) { .... i = j; }
1576 // In this case, j = {1,+,1} and BEValue is j.
1577 // Because the other in-value of i (0) fits the evolution of BEValue
1578 // i really is an addrec evolution.
1579 if (AddRec->getLoop() == L && AddRec->isAffine()) {
1580 SCEVHandle StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
1581
1582 // If StartVal = j.start - j.stride, we can use StartVal as the
1583 // initial step of the addrec evolution.
Dan Gohman89f85052007-10-22 18:31:58 +00001584 if (StartVal == SE.getMinusSCEV(AddRec->getOperand(0),
1585 AddRec->getOperand(1))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001586 SCEVHandle PHISCEV =
Dan Gohman89f85052007-10-22 18:31:58 +00001587 SE.getAddRecExpr(StartVal, AddRec->getOperand(1), L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001588
1589 // Okay, for the entire analysis of this edge we assumed the PHI
1590 // to be symbolic. We now need to go back and update all of the
1591 // entries for the scalars that use the PHI (except for the PHI
1592 // itself) to use the new analyzed value instead of the "symbolic"
1593 // value.
1594 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
1595 return PHISCEV;
1596 }
1597 }
1598 }
1599
1600 return SymbolicName;
1601 }
1602
1603 // If it's not a loop phi, we can't handle it yet.
Dan Gohman89f85052007-10-22 18:31:58 +00001604 return SE.getUnknown(PN);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001605}
1606
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001607/// GetMinTrailingZeros - Determine the minimum number of zero bits that S is
1608/// guaranteed to end in (at every loop iteration). It is, at the same time,
1609/// the minimum number of times S is divisible by 2. For example, given {4,+,8}
1610/// it returns 2. If S is guaranteed to be 0, it returns the bitwidth of S.
1611static uint32_t GetMinTrailingZeros(SCEVHandle S) {
1612 if (SCEVConstant *C = dyn_cast<SCEVConstant>(S))
Chris Lattner6ecce2a2007-11-23 22:36:49 +00001613 return C->getValue()->getValue().countTrailingZeros();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001614
Nick Lewycky3a8a41f2007-11-20 08:44:50 +00001615 if (SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001616 return std::min(GetMinTrailingZeros(T->getOperand()), T->getBitWidth());
1617
1618 if (SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
1619 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
1620 return OpRes == E->getOperand()->getBitWidth() ? E->getBitWidth() : OpRes;
1621 }
1622
1623 if (SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
1624 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
1625 return OpRes == E->getOperand()->getBitWidth() ? E->getBitWidth() : OpRes;
1626 }
1627
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001628 if (SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001629 // The result is the min of all operands results.
1630 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
1631 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
1632 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
1633 return MinOpRes;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001634 }
1635
1636 if (SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001637 // The result is the sum of all operands results.
1638 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0));
1639 uint32_t BitWidth = M->getBitWidth();
1640 for (unsigned i = 1, e = M->getNumOperands();
1641 SumOpRes != BitWidth && i != e; ++i)
1642 SumOpRes = std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)),
1643 BitWidth);
1644 return SumOpRes;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001645 }
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001646
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001647 if (SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001648 // The result is the min of all operands results.
1649 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
1650 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
1651 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
1652 return MinOpRes;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001653 }
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001654
Nick Lewycky711640a2007-11-25 22:41:31 +00001655 if (SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
1656 // The result is the min of all operands results.
1657 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
1658 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
1659 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
1660 return MinOpRes;
1661 }
1662
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001663 if (SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
1664 // The result is the min of all operands results.
1665 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
1666 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
1667 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
1668 return MinOpRes;
1669 }
1670
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +00001671 // SCEVUDivExpr, SCEVUnknown
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001672 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001673}
1674
1675/// createSCEV - We know that there is no SCEV for the specified value.
1676/// Analyze the expression.
1677///
1678SCEVHandle ScalarEvolutionsImpl::createSCEV(Value *V) {
Chris Lattner3fff4642007-11-23 08:46:22 +00001679 if (!isa<IntegerType>(V->getType()))
1680 return SE.getUnknown(V);
1681
Dan Gohman3996f472008-06-22 19:56:46 +00001682 unsigned Opcode = Instruction::UserOp1;
1683 if (Instruction *I = dyn_cast<Instruction>(V))
1684 Opcode = I->getOpcode();
1685 else if (ConstantExpr *CE = dyn_cast<ConstantExpr>(V))
1686 Opcode = CE->getOpcode();
1687 else
1688 return SE.getUnknown(V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001689
Dan Gohman3996f472008-06-22 19:56:46 +00001690 User *U = cast<User>(V);
1691 switch (Opcode) {
1692 case Instruction::Add:
1693 return SE.getAddExpr(getSCEV(U->getOperand(0)),
1694 getSCEV(U->getOperand(1)));
1695 case Instruction::Mul:
1696 return SE.getMulExpr(getSCEV(U->getOperand(0)),
1697 getSCEV(U->getOperand(1)));
1698 case Instruction::UDiv:
1699 return SE.getUDivExpr(getSCEV(U->getOperand(0)),
1700 getSCEV(U->getOperand(1)));
1701 case Instruction::Sub:
1702 return SE.getMinusSCEV(getSCEV(U->getOperand(0)),
1703 getSCEV(U->getOperand(1)));
1704 case Instruction::Or:
1705 // If the RHS of the Or is a constant, we may have something like:
1706 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop
1707 // optimizations will transparently handle this case.
1708 //
1709 // In order for this transformation to be safe, the LHS must be of the
1710 // form X*(2^n) and the Or constant must be less than 2^n.
1711 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
1712 SCEVHandle LHS = getSCEV(U->getOperand(0));
1713 const APInt &CIVal = CI->getValue();
1714 if (GetMinTrailingZeros(LHS) >=
1715 (CIVal.getBitWidth() - CIVal.countLeadingZeros()))
1716 return SE.getAddExpr(LHS, getSCEV(U->getOperand(1)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001717 }
Dan Gohman3996f472008-06-22 19:56:46 +00001718 break;
1719 case Instruction::Xor:
Dan Gohman3996f472008-06-22 19:56:46 +00001720 if (ConstantInt *CI = dyn_cast<ConstantInt>(U->getOperand(1))) {
Nick Lewycky7fd27892008-07-07 06:15:49 +00001721 // If the RHS of the xor is a signbit, then this is just an add.
1722 // Instcombine turns add of signbit into xor as a strength reduction step.
Dan Gohman3996f472008-06-22 19:56:46 +00001723 if (CI->getValue().isSignBit())
1724 return SE.getAddExpr(getSCEV(U->getOperand(0)),
1725 getSCEV(U->getOperand(1)));
Nick Lewycky7fd27892008-07-07 06:15:49 +00001726
1727 // If the RHS of xor is -1, then this is a not operation.
Dan Gohman3996f472008-06-22 19:56:46 +00001728 else if (CI->isAllOnesValue())
1729 return SE.getNotSCEV(getSCEV(U->getOperand(0)));
1730 }
1731 break;
1732
1733 case Instruction::Shl:
1734 // Turn shift left of a constant amount into a multiply.
1735 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
1736 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
1737 Constant *X = ConstantInt::get(
1738 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
1739 return SE.getMulExpr(getSCEV(U->getOperand(0)), getSCEV(X));
1740 }
1741 break;
1742
Nick Lewycky7fd27892008-07-07 06:15:49 +00001743 case Instruction::LShr:
1744 // Turn logical shift right of a constant into a unsigned divide.
1745 if (ConstantInt *SA = dyn_cast<ConstantInt>(U->getOperand(1))) {
1746 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
1747 Constant *X = ConstantInt::get(
1748 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
1749 return SE.getUDivExpr(getSCEV(U->getOperand(0)), getSCEV(X));
1750 }
1751 break;
1752
Dan Gohman3996f472008-06-22 19:56:46 +00001753 case Instruction::Trunc:
1754 return SE.getTruncateExpr(getSCEV(U->getOperand(0)), U->getType());
1755
1756 case Instruction::ZExt:
1757 return SE.getZeroExtendExpr(getSCEV(U->getOperand(0)), U->getType());
1758
1759 case Instruction::SExt:
1760 return SE.getSignExtendExpr(getSCEV(U->getOperand(0)), U->getType());
1761
1762 case Instruction::BitCast:
1763 // BitCasts are no-op casts so we just eliminate the cast.
1764 if (U->getType()->isInteger() &&
1765 U->getOperand(0)->getType()->isInteger())
1766 return getSCEV(U->getOperand(0));
1767 break;
1768
1769 case Instruction::PHI:
1770 return createNodeForPHI(cast<PHINode>(U));
1771
1772 case Instruction::Select:
1773 // This could be a smax or umax that was lowered earlier.
1774 // Try to recover it.
1775 if (ICmpInst *ICI = dyn_cast<ICmpInst>(U->getOperand(0))) {
1776 Value *LHS = ICI->getOperand(0);
1777 Value *RHS = ICI->getOperand(1);
1778 switch (ICI->getPredicate()) {
1779 case ICmpInst::ICMP_SLT:
1780 case ICmpInst::ICMP_SLE:
1781 std::swap(LHS, RHS);
1782 // fall through
1783 case ICmpInst::ICMP_SGT:
1784 case ICmpInst::ICMP_SGE:
1785 if (LHS == U->getOperand(1) && RHS == U->getOperand(2))
1786 return SE.getSMaxExpr(getSCEV(LHS), getSCEV(RHS));
1787 else if (LHS == U->getOperand(2) && RHS == U->getOperand(1))
1788 // -smax(-x, -y) == smin(x, y).
1789 return SE.getNegativeSCEV(SE.getSMaxExpr(
1790 SE.getNegativeSCEV(getSCEV(LHS)),
1791 SE.getNegativeSCEV(getSCEV(RHS))));
1792 break;
1793 case ICmpInst::ICMP_ULT:
1794 case ICmpInst::ICMP_ULE:
1795 std::swap(LHS, RHS);
1796 // fall through
1797 case ICmpInst::ICMP_UGT:
1798 case ICmpInst::ICMP_UGE:
1799 if (LHS == U->getOperand(1) && RHS == U->getOperand(2))
1800 return SE.getUMaxExpr(getSCEV(LHS), getSCEV(RHS));
1801 else if (LHS == U->getOperand(2) && RHS == U->getOperand(1))
1802 // ~umax(~x, ~y) == umin(x, y)
1803 return SE.getNotSCEV(SE.getUMaxExpr(SE.getNotSCEV(getSCEV(LHS)),
1804 SE.getNotSCEV(getSCEV(RHS))));
1805 break;
1806 default:
1807 break;
1808 }
1809 }
1810
1811 default: // We cannot analyze this expression.
1812 break;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001813 }
1814
Dan Gohman89f85052007-10-22 18:31:58 +00001815 return SE.getUnknown(V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001816}
1817
1818
1819
1820//===----------------------------------------------------------------------===//
1821// Iteration Count Computation Code
1822//
1823
1824/// getIterationCount - If the specified loop has a predictable iteration
1825/// count, return it. Note that it is not valid to call this method on a
1826/// loop without a loop-invariant iteration count.
1827SCEVHandle ScalarEvolutionsImpl::getIterationCount(const Loop *L) {
1828 std::map<const Loop*, SCEVHandle>::iterator I = IterationCounts.find(L);
1829 if (I == IterationCounts.end()) {
1830 SCEVHandle ItCount = ComputeIterationCount(L);
1831 I = IterationCounts.insert(std::make_pair(L, ItCount)).first;
1832 if (ItCount != UnknownValue) {
1833 assert(ItCount->isLoopInvariant(L) &&
1834 "Computed trip count isn't loop invariant for loop!");
1835 ++NumTripCountsComputed;
1836 } else if (isa<PHINode>(L->getHeader()->begin())) {
1837 // Only count loops that have phi nodes as not being computable.
1838 ++NumTripCountsNotComputed;
1839 }
1840 }
1841 return I->second;
1842}
1843
1844/// ComputeIterationCount - Compute the number of times the specified loop
1845/// will iterate.
1846SCEVHandle ScalarEvolutionsImpl::ComputeIterationCount(const Loop *L) {
1847 // If the loop has a non-one exit block count, we can't analyze it.
Devang Patel02451fa2007-08-21 00:31:24 +00001848 SmallVector<BasicBlock*, 8> ExitBlocks;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001849 L->getExitBlocks(ExitBlocks);
1850 if (ExitBlocks.size() != 1) return UnknownValue;
1851
1852 // Okay, there is one exit block. Try to find the condition that causes the
1853 // loop to be exited.
1854 BasicBlock *ExitBlock = ExitBlocks[0];
1855
1856 BasicBlock *ExitingBlock = 0;
1857 for (pred_iterator PI = pred_begin(ExitBlock), E = pred_end(ExitBlock);
1858 PI != E; ++PI)
1859 if (L->contains(*PI)) {
1860 if (ExitingBlock == 0)
1861 ExitingBlock = *PI;
1862 else
1863 return UnknownValue; // More than one block exiting!
1864 }
1865 assert(ExitingBlock && "No exits from loop, something is broken!");
1866
1867 // Okay, we've computed the exiting block. See what condition causes us to
1868 // exit.
1869 //
1870 // FIXME: we should be able to handle switch instructions (with a single exit)
1871 BranchInst *ExitBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
1872 if (ExitBr == 0) return UnknownValue;
1873 assert(ExitBr->isConditional() && "If unconditional, it can't be in loop!");
1874
1875 // At this point, we know we have a conditional branch that determines whether
1876 // the loop is exited. However, we don't know if the branch is executed each
1877 // time through the loop. If not, then the execution count of the branch will
1878 // not be equal to the trip count of the loop.
1879 //
1880 // Currently we check for this by checking to see if the Exit branch goes to
1881 // the loop header. If so, we know it will always execute the same number of
1882 // times as the loop. We also handle the case where the exit block *is* the
1883 // loop header. This is common for un-rotated loops. More extensive analysis
1884 // could be done to handle more cases here.
1885 if (ExitBr->getSuccessor(0) != L->getHeader() &&
1886 ExitBr->getSuccessor(1) != L->getHeader() &&
1887 ExitBr->getParent() != L->getHeader())
1888 return UnknownValue;
1889
1890 ICmpInst *ExitCond = dyn_cast<ICmpInst>(ExitBr->getCondition());
1891
Nick Lewyckyb3d24332008-02-21 08:34:02 +00001892 // If it's not an integer comparison then compute it the hard way.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001893 // Note that ICmpInst deals with pointer comparisons too so we must check
1894 // the type of the operand.
1895 if (ExitCond == 0 || isa<PointerType>(ExitCond->getOperand(0)->getType()))
1896 return ComputeIterationCountExhaustively(L, ExitBr->getCondition(),
1897 ExitBr->getSuccessor(0) == ExitBlock);
1898
1899 // If the condition was exit on true, convert the condition to exit on false
1900 ICmpInst::Predicate Cond;
1901 if (ExitBr->getSuccessor(1) == ExitBlock)
1902 Cond = ExitCond->getPredicate();
1903 else
1904 Cond = ExitCond->getInversePredicate();
1905
1906 // Handle common loops like: for (X = "string"; *X; ++X)
1907 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
1908 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
1909 SCEVHandle ItCnt =
1910 ComputeLoadConstantCompareIterationCount(LI, RHS, L, Cond);
1911 if (!isa<SCEVCouldNotCompute>(ItCnt)) return ItCnt;
1912 }
1913
1914 SCEVHandle LHS = getSCEV(ExitCond->getOperand(0));
1915 SCEVHandle RHS = getSCEV(ExitCond->getOperand(1));
1916
1917 // Try to evaluate any dependencies out of the loop.
1918 SCEVHandle Tmp = getSCEVAtScope(LHS, L);
1919 if (!isa<SCEVCouldNotCompute>(Tmp)) LHS = Tmp;
1920 Tmp = getSCEVAtScope(RHS, L);
1921 if (!isa<SCEVCouldNotCompute>(Tmp)) RHS = Tmp;
1922
1923 // At this point, we would like to compute how many iterations of the
1924 // loop the predicate will return true for these inputs.
Evan Cheng1d183082008-02-25 03:57:32 +00001925 if (isa<SCEVConstant>(LHS) && !isa<SCEVConstant>(RHS)) {
1926 // If there is a constant, force it into the RHS.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001927 std::swap(LHS, RHS);
1928 Cond = ICmpInst::getSwappedPredicate(Cond);
1929 }
1930
1931 // FIXME: think about handling pointer comparisons! i.e.:
1932 // while (P != P+100) ++P;
1933
1934 // If we have a comparison of a chrec against a constant, try to use value
1935 // ranges to answer this query.
1936 if (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
1937 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
1938 if (AddRec->getLoop() == L) {
1939 // Form the comparison range using the constant of the correct type so
1940 // that the ConstantRange class knows to do a signed or unsigned
1941 // comparison.
1942 ConstantInt *CompVal = RHSC->getValue();
1943 const Type *RealTy = ExitCond->getOperand(0)->getType();
1944 CompVal = dyn_cast<ConstantInt>(
1945 ConstantExpr::getBitCast(CompVal, RealTy));
1946 if (CompVal) {
1947 // Form the constant range.
1948 ConstantRange CompRange(
1949 ICmpInst::makeConstantRange(Cond, CompVal->getValue()));
1950
Dan Gohman89f85052007-10-22 18:31:58 +00001951 SCEVHandle Ret = AddRec->getNumIterationsInRange(CompRange, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001952 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
1953 }
1954 }
1955
1956 switch (Cond) {
1957 case ICmpInst::ICMP_NE: { // while (X != Y)
1958 // Convert to: while (X-Y != 0)
Dan Gohman89f85052007-10-22 18:31:58 +00001959 SCEVHandle TC = HowFarToZero(SE.getMinusSCEV(LHS, RHS), L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001960 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
1961 break;
1962 }
1963 case ICmpInst::ICMP_EQ: {
1964 // Convert to: while (X-Y == 0) // while (X == Y)
Dan Gohman89f85052007-10-22 18:31:58 +00001965 SCEVHandle TC = HowFarToNonZero(SE.getMinusSCEV(LHS, RHS), L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001966 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
1967 break;
1968 }
1969 case ICmpInst::ICMP_SLT: {
Nick Lewyckyb7c28942007-08-06 19:21:00 +00001970 SCEVHandle TC = HowManyLessThans(LHS, RHS, L, true);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001971 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
1972 break;
1973 }
1974 case ICmpInst::ICMP_SGT: {
Dan Gohman89f85052007-10-22 18:31:58 +00001975 SCEVHandle TC = HowManyLessThans(SE.getNegativeSCEV(LHS),
1976 SE.getNegativeSCEV(RHS), L, true);
Nick Lewyckyb7c28942007-08-06 19:21:00 +00001977 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
1978 break;
1979 }
1980 case ICmpInst::ICMP_ULT: {
1981 SCEVHandle TC = HowManyLessThans(LHS, RHS, L, false);
1982 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
1983 break;
1984 }
1985 case ICmpInst::ICMP_UGT: {
Dale Johannesend721b952008-04-20 16:58:57 +00001986 SCEVHandle TC = HowManyLessThans(SE.getNotSCEV(LHS),
Nick Lewycky347e4222008-05-06 04:03:18 +00001987 SE.getNotSCEV(RHS), L, false);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001988 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
1989 break;
1990 }
1991 default:
1992#if 0
1993 cerr << "ComputeIterationCount ";
1994 if (ExitCond->getOperand(0)->getType()->isUnsigned())
1995 cerr << "[unsigned] ";
1996 cerr << *LHS << " "
1997 << Instruction::getOpcodeName(Instruction::ICmp)
1998 << " " << *RHS << "\n";
1999#endif
2000 break;
2001 }
2002 return ComputeIterationCountExhaustively(L, ExitCond,
2003 ExitBr->getSuccessor(0) == ExitBlock);
2004}
2005
2006static ConstantInt *
Dan Gohman89f85052007-10-22 18:31:58 +00002007EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
2008 ScalarEvolution &SE) {
2009 SCEVHandle InVal = SE.getConstant(C);
2010 SCEVHandle Val = AddRec->evaluateAtIteration(InVal, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002011 assert(isa<SCEVConstant>(Val) &&
2012 "Evaluation of SCEV at constant didn't fold correctly?");
2013 return cast<SCEVConstant>(Val)->getValue();
2014}
2015
2016/// GetAddressedElementFromGlobal - Given a global variable with an initializer
2017/// and a GEP expression (missing the pointer index) indexing into it, return
2018/// the addressed element of the initializer or null if the index expression is
2019/// invalid.
2020static Constant *
2021GetAddressedElementFromGlobal(GlobalVariable *GV,
2022 const std::vector<ConstantInt*> &Indices) {
2023 Constant *Init = GV->getInitializer();
2024 for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
2025 uint64_t Idx = Indices[i]->getZExtValue();
2026 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
2027 assert(Idx < CS->getNumOperands() && "Bad struct index!");
2028 Init = cast<Constant>(CS->getOperand(Idx));
2029 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
2030 if (Idx >= CA->getNumOperands()) return 0; // Bogus program
2031 Init = cast<Constant>(CA->getOperand(Idx));
2032 } else if (isa<ConstantAggregateZero>(Init)) {
2033 if (const StructType *STy = dyn_cast<StructType>(Init->getType())) {
2034 assert(Idx < STy->getNumElements() && "Bad struct index!");
2035 Init = Constant::getNullValue(STy->getElementType(Idx));
2036 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Init->getType())) {
2037 if (Idx >= ATy->getNumElements()) return 0; // Bogus program
2038 Init = Constant::getNullValue(ATy->getElementType());
2039 } else {
2040 assert(0 && "Unknown constant aggregate type!");
2041 }
2042 return 0;
2043 } else {
2044 return 0; // Unknown initializer type
2045 }
2046 }
2047 return Init;
2048}
2049
2050/// ComputeLoadConstantCompareIterationCount - Given an exit condition of
Nick Lewycky347e4222008-05-06 04:03:18 +00002051/// 'icmp op load X, cst', try to see if we can compute the trip count.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002052SCEVHandle ScalarEvolutionsImpl::
2053ComputeLoadConstantCompareIterationCount(LoadInst *LI, Constant *RHS,
2054 const Loop *L,
2055 ICmpInst::Predicate predicate) {
2056 if (LI->isVolatile()) return UnknownValue;
2057
2058 // Check to see if the loaded pointer is a getelementptr of a global.
2059 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
2060 if (!GEP) return UnknownValue;
2061
2062 // Make sure that it is really a constant global we are gepping, with an
2063 // initializer, and make sure the first IDX is really 0.
2064 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
2065 if (!GV || !GV->isConstant() || !GV->hasInitializer() ||
2066 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
2067 !cast<Constant>(GEP->getOperand(1))->isNullValue())
2068 return UnknownValue;
2069
2070 // Okay, we allow one non-constant index into the GEP instruction.
2071 Value *VarIdx = 0;
2072 std::vector<ConstantInt*> Indexes;
2073 unsigned VarIdxNum = 0;
2074 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
2075 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
2076 Indexes.push_back(CI);
2077 } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
2078 if (VarIdx) return UnknownValue; // Multiple non-constant idx's.
2079 VarIdx = GEP->getOperand(i);
2080 VarIdxNum = i-2;
2081 Indexes.push_back(0);
2082 }
2083
2084 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
2085 // Check to see if X is a loop variant variable value now.
2086 SCEVHandle Idx = getSCEV(VarIdx);
2087 SCEVHandle Tmp = getSCEVAtScope(Idx, L);
2088 if (!isa<SCEVCouldNotCompute>(Tmp)) Idx = Tmp;
2089
2090 // We can only recognize very limited forms of loop index expressions, in
2091 // particular, only affine AddRec's like {C1,+,C2}.
2092 SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
2093 if (!IdxExpr || !IdxExpr->isAffine() || IdxExpr->isLoopInvariant(L) ||
2094 !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
2095 !isa<SCEVConstant>(IdxExpr->getOperand(1)))
2096 return UnknownValue;
2097
2098 unsigned MaxSteps = MaxBruteForceIterations;
2099 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
2100 ConstantInt *ItCst =
2101 ConstantInt::get(IdxExpr->getType(), IterationNum);
Dan Gohman89f85052007-10-22 18:31:58 +00002102 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002103
2104 // Form the GEP offset.
2105 Indexes[VarIdxNum] = Val;
2106
2107 Constant *Result = GetAddressedElementFromGlobal(GV, Indexes);
2108 if (Result == 0) break; // Cannot compute!
2109
2110 // Evaluate the condition for this iteration.
2111 Result = ConstantExpr::getICmp(predicate, Result, RHS);
2112 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure
2113 if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
2114#if 0
2115 cerr << "\n***\n*** Computed loop count " << *ItCst
2116 << "\n*** From global " << *GV << "*** BB: " << *L->getHeader()
2117 << "***\n";
2118#endif
2119 ++NumArrayLenItCounts;
Dan Gohman89f85052007-10-22 18:31:58 +00002120 return SE.getConstant(ItCst); // Found terminating iteration!
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002121 }
2122 }
2123 return UnknownValue;
2124}
2125
2126
2127/// CanConstantFold - Return true if we can constant fold an instruction of the
2128/// specified type, assuming that all operands were constants.
2129static bool CanConstantFold(const Instruction *I) {
2130 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
2131 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I))
2132 return true;
2133
2134 if (const CallInst *CI = dyn_cast<CallInst>(I))
2135 if (const Function *F = CI->getCalledFunction())
Dan Gohmane6e001f2008-01-31 01:05:10 +00002136 return canConstantFoldCallTo(F);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002137 return false;
2138}
2139
2140/// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
2141/// in the loop that V is derived from. We allow arbitrary operations along the
2142/// way, but the operands of an operation must either be constants or a value
2143/// derived from a constant PHI. If this expression does not fit with these
2144/// constraints, return null.
2145static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
2146 // If this is not an instruction, or if this is an instruction outside of the
2147 // loop, it can't be derived from a loop PHI.
2148 Instruction *I = dyn_cast<Instruction>(V);
2149 if (I == 0 || !L->contains(I->getParent())) return 0;
2150
Anton Korobeynikov357a27d2008-02-20 11:08:44 +00002151 if (PHINode *PN = dyn_cast<PHINode>(I)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002152 if (L->getHeader() == I->getParent())
2153 return PN;
2154 else
2155 // We don't currently keep track of the control flow needed to evaluate
2156 // PHIs, so we cannot handle PHIs inside of loops.
2157 return 0;
Anton Korobeynikov357a27d2008-02-20 11:08:44 +00002158 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002159
2160 // If we won't be able to constant fold this expression even if the operands
2161 // are constants, return early.
2162 if (!CanConstantFold(I)) return 0;
2163
2164 // Otherwise, we can evaluate this instruction if all of its operands are
2165 // constant or derived from a PHI node themselves.
2166 PHINode *PHI = 0;
2167 for (unsigned Op = 0, e = I->getNumOperands(); Op != e; ++Op)
2168 if (!(isa<Constant>(I->getOperand(Op)) ||
2169 isa<GlobalValue>(I->getOperand(Op)))) {
2170 PHINode *P = getConstantEvolvingPHI(I->getOperand(Op), L);
2171 if (P == 0) return 0; // Not evolving from PHI
2172 if (PHI == 0)
2173 PHI = P;
2174 else if (PHI != P)
2175 return 0; // Evolving from multiple different PHIs.
2176 }
2177
2178 // This is a expression evolving from a constant PHI!
2179 return PHI;
2180}
2181
2182/// EvaluateExpression - Given an expression that passes the
2183/// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
2184/// in the loop has the value PHIVal. If we can't fold this expression for some
2185/// reason, return null.
2186static Constant *EvaluateExpression(Value *V, Constant *PHIVal) {
2187 if (isa<PHINode>(V)) return PHIVal;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002188 if (Constant *C = dyn_cast<Constant>(V)) return C;
2189 Instruction *I = cast<Instruction>(V);
2190
2191 std::vector<Constant*> Operands;
2192 Operands.resize(I->getNumOperands());
2193
2194 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
2195 Operands[i] = EvaluateExpression(I->getOperand(i), PHIVal);
2196 if (Operands[i] == 0) return 0;
2197 }
2198
Chris Lattnerd6e56912007-12-10 22:53:04 +00002199 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
2200 return ConstantFoldCompareInstOperands(CI->getPredicate(),
2201 &Operands[0], Operands.size());
2202 else
2203 return ConstantFoldInstOperands(I->getOpcode(), I->getType(),
2204 &Operands[0], Operands.size());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002205}
2206
2207/// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
2208/// in the header of its containing loop, we know the loop executes a
2209/// constant number of times, and the PHI node is just a recurrence
2210/// involving constants, fold it.
2211Constant *ScalarEvolutionsImpl::
2212getConstantEvolutionLoopExitValue(PHINode *PN, const APInt& Its, const Loop *L){
2213 std::map<PHINode*, Constant*>::iterator I =
2214 ConstantEvolutionLoopExitValue.find(PN);
2215 if (I != ConstantEvolutionLoopExitValue.end())
2216 return I->second;
2217
2218 if (Its.ugt(APInt(Its.getBitWidth(),MaxBruteForceIterations)))
2219 return ConstantEvolutionLoopExitValue[PN] = 0; // Not going to evaluate it.
2220
2221 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
2222
2223 // Since the loop is canonicalized, the PHI node must have two entries. One
2224 // entry must be a constant (coming in from outside of the loop), and the
2225 // second must be derived from the same PHI.
2226 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
2227 Constant *StartCST =
2228 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
2229 if (StartCST == 0)
2230 return RetVal = 0; // Must be a constant.
2231
2232 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
2233 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
2234 if (PN2 != PN)
2235 return RetVal = 0; // Not derived from same PHI.
2236
2237 // Execute the loop symbolically to determine the exit value.
2238 if (Its.getActiveBits() >= 32)
2239 return RetVal = 0; // More than 2^32-1 iterations?? Not doing it!
2240
2241 unsigned NumIterations = Its.getZExtValue(); // must be in range
2242 unsigned IterationNum = 0;
2243 for (Constant *PHIVal = StartCST; ; ++IterationNum) {
2244 if (IterationNum == NumIterations)
2245 return RetVal = PHIVal; // Got exit value!
2246
2247 // Compute the value of the PHI node for the next iteration.
2248 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
2249 if (NextPHI == PHIVal)
2250 return RetVal = NextPHI; // Stopped evolving!
2251 if (NextPHI == 0)
2252 return 0; // Couldn't evaluate!
2253 PHIVal = NextPHI;
2254 }
2255}
2256
2257/// ComputeIterationCountExhaustively - If the trip is known to execute a
2258/// constant number of times (the condition evolves only from constants),
2259/// try to evaluate a few iterations of the loop until we get the exit
2260/// condition gets a value of ExitWhen (true or false). If we cannot
2261/// evaluate the trip count of the loop, return UnknownValue.
2262SCEVHandle ScalarEvolutionsImpl::
2263ComputeIterationCountExhaustively(const Loop *L, Value *Cond, bool ExitWhen) {
2264 PHINode *PN = getConstantEvolvingPHI(Cond, L);
2265 if (PN == 0) return UnknownValue;
2266
2267 // Since the loop is canonicalized, the PHI node must have two entries. One
2268 // entry must be a constant (coming in from outside of the loop), and the
2269 // second must be derived from the same PHI.
2270 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
2271 Constant *StartCST =
2272 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
2273 if (StartCST == 0) return UnknownValue; // Must be a constant.
2274
2275 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
2276 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
2277 if (PN2 != PN) return UnknownValue; // Not derived from same PHI.
2278
2279 // Okay, we find a PHI node that defines the trip count of this loop. Execute
2280 // the loop symbolically to determine when the condition gets a value of
2281 // "ExitWhen".
2282 unsigned IterationNum = 0;
2283 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis.
2284 for (Constant *PHIVal = StartCST;
2285 IterationNum != MaxIterations; ++IterationNum) {
2286 ConstantInt *CondVal =
2287 dyn_cast_or_null<ConstantInt>(EvaluateExpression(Cond, PHIVal));
2288
2289 // Couldn't symbolically evaluate.
2290 if (!CondVal) return UnknownValue;
2291
2292 if (CondVal->getValue() == uint64_t(ExitWhen)) {
2293 ConstantEvolutionLoopExitValue[PN] = PHIVal;
2294 ++NumBruteForceTripCountsComputed;
Dan Gohman89f85052007-10-22 18:31:58 +00002295 return SE.getConstant(ConstantInt::get(Type::Int32Ty, IterationNum));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002296 }
2297
2298 // Compute the value of the PHI node for the next iteration.
2299 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
2300 if (NextPHI == 0 || NextPHI == PHIVal)
2301 return UnknownValue; // Couldn't evaluate or not making progress...
2302 PHIVal = NextPHI;
2303 }
2304
2305 // Too many iterations were needed to evaluate.
2306 return UnknownValue;
2307}
2308
2309/// getSCEVAtScope - Compute the value of the specified expression within the
2310/// indicated loop (which may be null to indicate in no loop). If the
2311/// expression cannot be evaluated, return UnknownValue.
2312SCEVHandle ScalarEvolutionsImpl::getSCEVAtScope(SCEV *V, const Loop *L) {
2313 // FIXME: this should be turned into a virtual method on SCEV!
2314
2315 if (isa<SCEVConstant>(V)) return V;
2316
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00002317 // If this instruction is evolved from a constant-evolving PHI, compute the
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002318 // exit value from the loop without using SCEVs.
2319 if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
2320 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
2321 const Loop *LI = this->LI[I->getParent()];
2322 if (LI && LI->getParentLoop() == L) // Looking for loop exit value.
2323 if (PHINode *PN = dyn_cast<PHINode>(I))
2324 if (PN->getParent() == LI->getHeader()) {
2325 // Okay, there is no closed form solution for the PHI node. Check
2326 // to see if the loop that contains it has a known iteration count.
2327 // If so, we may be able to force computation of the exit value.
2328 SCEVHandle IterationCount = getIterationCount(LI);
2329 if (SCEVConstant *ICC = dyn_cast<SCEVConstant>(IterationCount)) {
2330 // Okay, we know how many times the containing loop executes. If
2331 // this is a constant evolving PHI node, get the final value at
2332 // the specified iteration number.
2333 Constant *RV = getConstantEvolutionLoopExitValue(PN,
2334 ICC->getValue()->getValue(),
2335 LI);
Dan Gohman89f85052007-10-22 18:31:58 +00002336 if (RV) return SE.getUnknown(RV);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002337 }
2338 }
2339
2340 // Okay, this is an expression that we cannot symbolically evaluate
2341 // into a SCEV. Check to see if it's possible to symbolically evaluate
2342 // the arguments into constants, and if so, try to constant propagate the
2343 // result. This is particularly useful for computing loop exit values.
2344 if (CanConstantFold(I)) {
2345 std::vector<Constant*> Operands;
2346 Operands.reserve(I->getNumOperands());
2347 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
2348 Value *Op = I->getOperand(i);
2349 if (Constant *C = dyn_cast<Constant>(Op)) {
2350 Operands.push_back(C);
2351 } else {
Chris Lattner3fff4642007-11-23 08:46:22 +00002352 // If any of the operands is non-constant and if they are
2353 // non-integer, don't even try to analyze them with scev techniques.
2354 if (!isa<IntegerType>(Op->getType()))
2355 return V;
2356
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002357 SCEVHandle OpV = getSCEVAtScope(getSCEV(Op), L);
2358 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(OpV))
2359 Operands.push_back(ConstantExpr::getIntegerCast(SC->getValue(),
2360 Op->getType(),
2361 false));
2362 else if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(OpV)) {
2363 if (Constant *C = dyn_cast<Constant>(SU->getValue()))
2364 Operands.push_back(ConstantExpr::getIntegerCast(C,
2365 Op->getType(),
2366 false));
2367 else
2368 return V;
2369 } else {
2370 return V;
2371 }
2372 }
2373 }
Chris Lattnerd6e56912007-12-10 22:53:04 +00002374
2375 Constant *C;
2376 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
2377 C = ConstantFoldCompareInstOperands(CI->getPredicate(),
2378 &Operands[0], Operands.size());
2379 else
2380 C = ConstantFoldInstOperands(I->getOpcode(), I->getType(),
2381 &Operands[0], Operands.size());
Dan Gohman89f85052007-10-22 18:31:58 +00002382 return SE.getUnknown(C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002383 }
2384 }
2385
2386 // This is some other type of SCEVUnknown, just return it.
2387 return V;
2388 }
2389
2390 if (SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
2391 // Avoid performing the look-up in the common case where the specified
2392 // expression has no loop-variant portions.
2393 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
2394 SCEVHandle OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
2395 if (OpAtScope != Comm->getOperand(i)) {
2396 if (OpAtScope == UnknownValue) return UnknownValue;
2397 // Okay, at least one of these operands is loop variant but might be
2398 // foldable. Build a new instance of the folded commutative expression.
2399 std::vector<SCEVHandle> NewOps(Comm->op_begin(), Comm->op_begin()+i);
2400 NewOps.push_back(OpAtScope);
2401
2402 for (++i; i != e; ++i) {
2403 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
2404 if (OpAtScope == UnknownValue) return UnknownValue;
2405 NewOps.push_back(OpAtScope);
2406 }
2407 if (isa<SCEVAddExpr>(Comm))
Dan Gohman89f85052007-10-22 18:31:58 +00002408 return SE.getAddExpr(NewOps);
Nick Lewycky711640a2007-11-25 22:41:31 +00002409 if (isa<SCEVMulExpr>(Comm))
2410 return SE.getMulExpr(NewOps);
2411 if (isa<SCEVSMaxExpr>(Comm))
2412 return SE.getSMaxExpr(NewOps);
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00002413 if (isa<SCEVUMaxExpr>(Comm))
2414 return SE.getUMaxExpr(NewOps);
Nick Lewycky711640a2007-11-25 22:41:31 +00002415 assert(0 && "Unknown commutative SCEV type!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002416 }
2417 }
2418 // If we got here, all operands are loop invariant.
2419 return Comm;
2420 }
2421
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +00002422 if (SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002423 SCEVHandle LHS = getSCEVAtScope(Div->getLHS(), L);
2424 if (LHS == UnknownValue) return LHS;
2425 SCEVHandle RHS = getSCEVAtScope(Div->getRHS(), L);
2426 if (RHS == UnknownValue) return RHS;
2427 if (LHS == Div->getLHS() && RHS == Div->getRHS())
2428 return Div; // must be loop invariant
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +00002429 return SE.getUDivExpr(LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002430 }
2431
2432 // If this is a loop recurrence for a loop that does not contain L, then we
2433 // are dealing with the final value computed by the loop.
2434 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
2435 if (!L || !AddRec->getLoop()->contains(L->getHeader())) {
2436 // To evaluate this recurrence, we need to know how many times the AddRec
2437 // loop iterates. Compute this now.
2438 SCEVHandle IterationCount = getIterationCount(AddRec->getLoop());
2439 if (IterationCount == UnknownValue) return UnknownValue;
Nick Lewyckydbaa60a2008-06-13 04:38:55 +00002440 IterationCount = SE.getTruncateOrZeroExtend(IterationCount,
2441 AddRec->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002442
2443 // If the value is affine, simplify the expression evaluation to just
2444 // Start + Step*IterationCount.
2445 if (AddRec->isAffine())
Dan Gohman89f85052007-10-22 18:31:58 +00002446 return SE.getAddExpr(AddRec->getStart(),
2447 SE.getMulExpr(IterationCount,
2448 AddRec->getOperand(1)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002449
2450 // Otherwise, evaluate it the hard way.
Dan Gohman89f85052007-10-22 18:31:58 +00002451 return AddRec->evaluateAtIteration(IterationCount, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002452 }
2453 return UnknownValue;
2454 }
2455
2456 //assert(0 && "Unknown SCEV type!");
2457 return UnknownValue;
2458}
2459
2460
2461/// SolveQuadraticEquation - Find the roots of the quadratic equation for the
2462/// given quadratic chrec {L,+,M,+,N}. This returns either the two roots (which
2463/// might be the same) or two SCEVCouldNotCompute objects.
2464///
2465static std::pair<SCEVHandle,SCEVHandle>
Dan Gohman89f85052007-10-22 18:31:58 +00002466SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002467 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
2468 SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
2469 SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
2470 SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
2471
2472 // We currently can only solve this if the coefficients are constants.
2473 if (!LC || !MC || !NC) {
2474 SCEV *CNC = new SCEVCouldNotCompute();
2475 return std::make_pair(CNC, CNC);
2476 }
2477
2478 uint32_t BitWidth = LC->getValue()->getValue().getBitWidth();
2479 const APInt &L = LC->getValue()->getValue();
2480 const APInt &M = MC->getValue()->getValue();
2481 const APInt &N = NC->getValue()->getValue();
2482 APInt Two(BitWidth, 2);
2483 APInt Four(BitWidth, 4);
2484
2485 {
2486 using namespace APIntOps;
2487 const APInt& C = L;
2488 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
2489 // The B coefficient is M-N/2
2490 APInt B(M);
2491 B -= sdiv(N,Two);
2492
2493 // The A coefficient is N/2
2494 APInt A(N.sdiv(Two));
2495
2496 // Compute the B^2-4ac term.
2497 APInt SqrtTerm(B);
2498 SqrtTerm *= B;
2499 SqrtTerm -= Four * (A * C);
2500
2501 // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest
2502 // integer value or else APInt::sqrt() will assert.
2503 APInt SqrtVal(SqrtTerm.sqrt());
2504
2505 // Compute the two solutions for the quadratic formula.
2506 // The divisions must be performed as signed divisions.
2507 APInt NegB(-B);
2508 APInt TwoA( A << 1 );
2509 ConstantInt *Solution1 = ConstantInt::get((NegB + SqrtVal).sdiv(TwoA));
2510 ConstantInt *Solution2 = ConstantInt::get((NegB - SqrtVal).sdiv(TwoA));
2511
Dan Gohman89f85052007-10-22 18:31:58 +00002512 return std::make_pair(SE.getConstant(Solution1),
2513 SE.getConstant(Solution2));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002514 } // end APIntOps namespace
2515}
2516
2517/// HowFarToZero - Return the number of times a backedge comparing the specified
2518/// value to zero will execute. If not computable, return UnknownValue
2519SCEVHandle ScalarEvolutionsImpl::HowFarToZero(SCEV *V, const Loop *L) {
2520 // If the value is a constant
2521 if (SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
2522 // If the value is already zero, the branch will execute zero times.
2523 if (C->getValue()->isZero()) return C;
2524 return UnknownValue; // Otherwise it will loop infinitely.
2525 }
2526
2527 SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
2528 if (!AddRec || AddRec->getLoop() != L)
2529 return UnknownValue;
2530
2531 if (AddRec->isAffine()) {
2532 // If this is an affine expression the execution count of this branch is
2533 // equal to:
2534 //
2535 // (0 - Start/Step) iff Start % Step == 0
2536 //
2537 // Get the initial value for the loop.
2538 SCEVHandle Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
2539 if (isa<SCEVCouldNotCompute>(Start)) return UnknownValue;
2540 SCEVHandle Step = AddRec->getOperand(1);
2541
2542 Step = getSCEVAtScope(Step, L->getParentLoop());
2543
2544 // Figure out if Start % Step == 0.
2545 // FIXME: We should add DivExpr and RemExpr operations to our AST.
2546 if (SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step)) {
2547 if (StepC->getValue()->equalsInt(1)) // N % 1 == 0
Dan Gohman89f85052007-10-22 18:31:58 +00002548 return SE.getNegativeSCEV(Start); // 0 - Start/1 == -Start
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002549 if (StepC->getValue()->isAllOnesValue()) // N % -1 == 0
2550 return Start; // 0 - Start/-1 == Start
2551
2552 // Check to see if Start is divisible by SC with no remainder.
2553 if (SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start)) {
2554 ConstantInt *StartCC = StartC->getValue();
2555 Constant *StartNegC = ConstantExpr::getNeg(StartCC);
Nick Lewycky96b38012008-05-25 23:43:32 +00002556 Constant *Rem = ConstantExpr::getURem(StartNegC, StepC->getValue());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002557 if (Rem->isNullValue()) {
Nick Lewycky96b38012008-05-25 23:43:32 +00002558 Constant *Result = ConstantExpr::getUDiv(StartNegC,StepC->getValue());
Dan Gohman89f85052007-10-22 18:31:58 +00002559 return SE.getUnknown(Result);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002560 }
2561 }
2562 }
2563 } else if (AddRec->isQuadratic() && AddRec->getType()->isInteger()) {
2564 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
2565 // the quadratic equation to solve it.
Dan Gohman89f85052007-10-22 18:31:58 +00002566 std::pair<SCEVHandle,SCEVHandle> Roots = SolveQuadraticEquation(AddRec, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002567 SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
2568 SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
2569 if (R1) {
2570#if 0
2571 cerr << "HFTZ: " << *V << " - sol#1: " << *R1
2572 << " sol#2: " << *R2 << "\n";
2573#endif
2574 // Pick the smallest positive root value.
2575 if (ConstantInt *CB =
2576 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
2577 R1->getValue(), R2->getValue()))) {
2578 if (CB->getZExtValue() == false)
2579 std::swap(R1, R2); // R1 is the minimum root now.
2580
2581 // We can only use this value if the chrec ends up with an exact zero
2582 // value at this index. When solving for "X*X != 5", for example, we
2583 // should not accept a root of 2.
Dan Gohman89f85052007-10-22 18:31:58 +00002584 SCEVHandle Val = AddRec->evaluateAtIteration(R1, SE);
Dan Gohman7b560c42008-06-18 16:23:07 +00002585 if (Val->isZero())
2586 return R1; // We found a quadratic root!
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002587 }
2588 }
2589 }
2590
2591 return UnknownValue;
2592}
2593
2594/// HowFarToNonZero - Return the number of times a backedge checking the
2595/// specified value for nonzero will execute. If not computable, return
2596/// UnknownValue
2597SCEVHandle ScalarEvolutionsImpl::HowFarToNonZero(SCEV *V, const Loop *L) {
2598 // Loops that look like: while (X == 0) are very strange indeed. We don't
2599 // handle them yet except for the trivial case. This could be expanded in the
2600 // future as needed.
2601
2602 // If the value is a constant, check to see if it is known to be non-zero
2603 // already. If so, the backedge will execute zero times.
2604 if (SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
Nick Lewyckyf6805182008-02-21 09:14:53 +00002605 if (!C->getValue()->isNullValue())
2606 return SE.getIntegerSCEV(0, C->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002607 return UnknownValue; // Otherwise it will loop infinitely.
2608 }
2609
2610 // We could implement others, but I really doubt anyone writes loops like
2611 // this, and if they did, they would already be constant folded.
2612 return UnknownValue;
2613}
2614
2615/// HowManyLessThans - Return the number of times a backedge containing the
2616/// specified less-than comparison will execute. If not computable, return
2617/// UnknownValue.
2618SCEVHandle ScalarEvolutionsImpl::
Nick Lewyckyb7c28942007-08-06 19:21:00 +00002619HowManyLessThans(SCEV *LHS, SCEV *RHS, const Loop *L, bool isSigned) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002620 // Only handle: "ADDREC < LoopInvariant".
2621 if (!RHS->isLoopInvariant(L)) return UnknownValue;
2622
2623 SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS);
2624 if (!AddRec || AddRec->getLoop() != L)
2625 return UnknownValue;
2626
2627 if (AddRec->isAffine()) {
2628 // FORNOW: We only support unit strides.
Dan Gohman89f85052007-10-22 18:31:58 +00002629 SCEVHandle One = SE.getIntegerSCEV(1, RHS->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002630 if (AddRec->getOperand(1) != One)
2631 return UnknownValue;
2632
Wojciech Matyjewiczebc77b12008-02-13 11:51:34 +00002633 // We know the LHS is of the form {n,+,1} and the RHS is some loop-invariant
2634 // m. So, we count the number of iterations in which {n,+,1} < m is true.
2635 // Note that we cannot simply return max(m-n,0) because it's not safe to
Wojciech Matyjewicz1377a542008-02-13 12:21:32 +00002636 // treat m-n as signed nor unsigned due to overflow possibility.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002637
Wojciech Matyjewiczebc77b12008-02-13 11:51:34 +00002638 // First, we get the value of the LHS in the first iteration: n
2639 SCEVHandle Start = AddRec->getOperand(0);
2640
2641 // Then, we get the value of the LHS in the first iteration in which the
2642 // above condition doesn't hold. This equals to max(m,n).
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00002643 SCEVHandle End = isSigned ? SE.getSMaxExpr(RHS, Start)
2644 : SE.getUMaxExpr(RHS, Start);
Wojciech Matyjewiczebc77b12008-02-13 11:51:34 +00002645
2646 // Finally, we subtract these two values to get the number of times the
2647 // backedge is executed: max(m,n)-n.
Wojciech Matyjewicza5718fc2008-02-12 15:09:36 +00002648 return SE.getMinusSCEV(End, Start);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002649 }
2650
2651 return UnknownValue;
2652}
2653
2654/// getNumIterationsInRange - Return the number of iterations of this loop that
2655/// produce values in the specified constant range. Another way of looking at
2656/// this is that it returns the first iteration number where the value is not in
2657/// the condition, thus computing the exit count. If the iteration count can't
2658/// be computed, an instance of SCEVCouldNotCompute is returned.
Dan Gohman89f85052007-10-22 18:31:58 +00002659SCEVHandle SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range,
2660 ScalarEvolution &SE) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002661 if (Range.isFullSet()) // Infinite loop.
2662 return new SCEVCouldNotCompute();
2663
2664 // If the start is a non-zero constant, shift the range to simplify things.
2665 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
2666 if (!SC->getValue()->isZero()) {
2667 std::vector<SCEVHandle> Operands(op_begin(), op_end());
Dan Gohman89f85052007-10-22 18:31:58 +00002668 Operands[0] = SE.getIntegerSCEV(0, SC->getType());
2669 SCEVHandle Shifted = SE.getAddRecExpr(Operands, getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002670 if (SCEVAddRecExpr *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted))
2671 return ShiftedAddRec->getNumIterationsInRange(
Dan Gohman89f85052007-10-22 18:31:58 +00002672 Range.subtract(SC->getValue()->getValue()), SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002673 // This is strange and shouldn't happen.
2674 return new SCEVCouldNotCompute();
2675 }
2676
2677 // The only time we can solve this is when we have all constant indices.
2678 // Otherwise, we cannot determine the overflow conditions.
2679 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
2680 if (!isa<SCEVConstant>(getOperand(i)))
2681 return new SCEVCouldNotCompute();
2682
2683
2684 // Okay at this point we know that all elements of the chrec are constants and
2685 // that the start element is zero.
2686
2687 // First check to see if the range contains zero. If not, the first
2688 // iteration exits.
2689 if (!Range.contains(APInt(getBitWidth(),0)))
Dan Gohman89f85052007-10-22 18:31:58 +00002690 return SE.getConstant(ConstantInt::get(getType(),0));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002691
2692 if (isAffine()) {
2693 // If this is an affine expression then we have this situation:
2694 // Solve {0,+,A} in Range === Ax in Range
2695
2696 // We know that zero is in the range. If A is positive then we know that
2697 // the upper value of the range must be the first possible exit value.
2698 // If A is negative then the lower of the range is the last possible loop
2699 // value. Also note that we already checked for a full range.
2700 APInt One(getBitWidth(),1);
2701 APInt A = cast<SCEVConstant>(getOperand(1))->getValue()->getValue();
2702 APInt End = A.sge(One) ? (Range.getUpper() - One) : Range.getLower();
2703
2704 // The exit value should be (End+A)/A.
Nick Lewyckya0facae2007-09-27 14:12:54 +00002705 APInt ExitVal = (End + A).udiv(A);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002706 ConstantInt *ExitValue = ConstantInt::get(ExitVal);
2707
2708 // Evaluate at the exit value. If we really did fall out of the valid
2709 // range, then we computed our trip count, otherwise wrap around or other
2710 // things must have happened.
Dan Gohman89f85052007-10-22 18:31:58 +00002711 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002712 if (Range.contains(Val->getValue()))
2713 return new SCEVCouldNotCompute(); // Something strange happened
2714
2715 // Ensure that the previous value is in the range. This is a sanity check.
2716 assert(Range.contains(
2717 EvaluateConstantChrecAtConstant(this,
Dan Gohman89f85052007-10-22 18:31:58 +00002718 ConstantInt::get(ExitVal - One), SE)->getValue()) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002719 "Linear scev computation is off in a bad way!");
Dan Gohman89f85052007-10-22 18:31:58 +00002720 return SE.getConstant(ExitValue);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002721 } else if (isQuadratic()) {
2722 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
2723 // quadratic equation to solve it. To do this, we must frame our problem in
2724 // terms of figuring out when zero is crossed, instead of when
2725 // Range.getUpper() is crossed.
2726 std::vector<SCEVHandle> NewOps(op_begin(), op_end());
Dan Gohman89f85052007-10-22 18:31:58 +00002727 NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper()));
2728 SCEVHandle NewAddRec = SE.getAddRecExpr(NewOps, getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002729
2730 // Next, solve the constructed addrec
2731 std::pair<SCEVHandle,SCEVHandle> Roots =
Dan Gohman89f85052007-10-22 18:31:58 +00002732 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002733 SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
2734 SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
2735 if (R1) {
2736 // Pick the smallest positive root value.
2737 if (ConstantInt *CB =
2738 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
2739 R1->getValue(), R2->getValue()))) {
2740 if (CB->getZExtValue() == false)
2741 std::swap(R1, R2); // R1 is the minimum root now.
2742
2743 // Make sure the root is not off by one. The returned iteration should
2744 // not be in the range, but the previous one should be. When solving
2745 // for "X*X < 5", for example, we should not return a root of 2.
2746 ConstantInt *R1Val = EvaluateConstantChrecAtConstant(this,
Dan Gohman89f85052007-10-22 18:31:58 +00002747 R1->getValue(),
2748 SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002749 if (Range.contains(R1Val->getValue())) {
2750 // The next iteration must be out of the range...
2751 ConstantInt *NextVal = ConstantInt::get(R1->getValue()->getValue()+1);
2752
Dan Gohman89f85052007-10-22 18:31:58 +00002753 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002754 if (!Range.contains(R1Val->getValue()))
Dan Gohman89f85052007-10-22 18:31:58 +00002755 return SE.getConstant(NextVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002756 return new SCEVCouldNotCompute(); // Something strange happened
2757 }
2758
2759 // If R1 was not in the range, then it is a good return value. Make
2760 // sure that R1-1 WAS in the range though, just in case.
2761 ConstantInt *NextVal = ConstantInt::get(R1->getValue()->getValue()-1);
Dan Gohman89f85052007-10-22 18:31:58 +00002762 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002763 if (Range.contains(R1Val->getValue()))
2764 return R1;
2765 return new SCEVCouldNotCompute(); // Something strange happened
2766 }
2767 }
2768 }
2769
2770 // Fallback, if this is a general polynomial, figure out the progression
2771 // through brute force: evaluate until we find an iteration that fails the
2772 // test. This is likely to be slow, but getting an accurate trip count is
2773 // incredibly important, we will be able to simplify the exit test a lot, and
2774 // we are almost guaranteed to get a trip count in this case.
2775 ConstantInt *TestVal = ConstantInt::get(getType(), 0);
2776 ConstantInt *EndVal = TestVal; // Stop when we wrap around.
2777 do {
2778 ++NumBruteForceEvaluations;
Dan Gohman89f85052007-10-22 18:31:58 +00002779 SCEVHandle Val = evaluateAtIteration(SE.getConstant(TestVal), SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002780 if (!isa<SCEVConstant>(Val)) // This shouldn't happen.
2781 return new SCEVCouldNotCompute();
2782
2783 // Check to see if we found the value!
2784 if (!Range.contains(cast<SCEVConstant>(Val)->getValue()->getValue()))
Dan Gohman89f85052007-10-22 18:31:58 +00002785 return SE.getConstant(TestVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002786
2787 // Increment to test the next index.
2788 TestVal = ConstantInt::get(TestVal->getValue()+1);
2789 } while (TestVal != EndVal);
2790
2791 return new SCEVCouldNotCompute();
2792}
2793
2794
2795
2796//===----------------------------------------------------------------------===//
2797// ScalarEvolution Class Implementation
2798//===----------------------------------------------------------------------===//
2799
2800bool ScalarEvolution::runOnFunction(Function &F) {
Dan Gohman89f85052007-10-22 18:31:58 +00002801 Impl = new ScalarEvolutionsImpl(*this, F, getAnalysis<LoopInfo>());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002802 return false;
2803}
2804
2805void ScalarEvolution::releaseMemory() {
2806 delete (ScalarEvolutionsImpl*)Impl;
2807 Impl = 0;
2808}
2809
2810void ScalarEvolution::getAnalysisUsage(AnalysisUsage &AU) const {
2811 AU.setPreservesAll();
2812 AU.addRequiredTransitive<LoopInfo>();
2813}
2814
2815SCEVHandle ScalarEvolution::getSCEV(Value *V) const {
2816 return ((ScalarEvolutionsImpl*)Impl)->getSCEV(V);
2817}
2818
2819/// hasSCEV - Return true if the SCEV for this value has already been
2820/// computed.
2821bool ScalarEvolution::hasSCEV(Value *V) const {
2822 return ((ScalarEvolutionsImpl*)Impl)->hasSCEV(V);
2823}
2824
2825
2826/// setSCEV - Insert the specified SCEV into the map of current SCEVs for
2827/// the specified value.
2828void ScalarEvolution::setSCEV(Value *V, const SCEVHandle &H) {
2829 ((ScalarEvolutionsImpl*)Impl)->setSCEV(V, H);
2830}
2831
2832
2833SCEVHandle ScalarEvolution::getIterationCount(const Loop *L) const {
2834 return ((ScalarEvolutionsImpl*)Impl)->getIterationCount(L);
2835}
2836
2837bool ScalarEvolution::hasLoopInvariantIterationCount(const Loop *L) const {
2838 return !isa<SCEVCouldNotCompute>(getIterationCount(L));
2839}
2840
2841SCEVHandle ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) const {
2842 return ((ScalarEvolutionsImpl*)Impl)->getSCEVAtScope(getSCEV(V), L);
2843}
2844
2845void ScalarEvolution::deleteValueFromRecords(Value *V) const {
2846 return ((ScalarEvolutionsImpl*)Impl)->deleteValueFromRecords(V);
2847}
2848
2849static void PrintLoopInfo(std::ostream &OS, const ScalarEvolution *SE,
2850 const Loop *L) {
2851 // Print all inner loops first
2852 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
2853 PrintLoopInfo(OS, SE, *I);
2854
Nick Lewyckye5da1912008-01-02 02:49:20 +00002855 OS << "Loop " << L->getHeader()->getName() << ": ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002856
Devang Patel02451fa2007-08-21 00:31:24 +00002857 SmallVector<BasicBlock*, 8> ExitBlocks;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002858 L->getExitBlocks(ExitBlocks);
2859 if (ExitBlocks.size() != 1)
Nick Lewyckye5da1912008-01-02 02:49:20 +00002860 OS << "<multiple exits> ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002861
2862 if (SE->hasLoopInvariantIterationCount(L)) {
Nick Lewyckye5da1912008-01-02 02:49:20 +00002863 OS << *SE->getIterationCount(L) << " iterations! ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002864 } else {
Nick Lewyckye5da1912008-01-02 02:49:20 +00002865 OS << "Unpredictable iteration count. ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002866 }
2867
Nick Lewyckye5da1912008-01-02 02:49:20 +00002868 OS << "\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002869}
2870
2871void ScalarEvolution::print(std::ostream &OS, const Module* ) const {
2872 Function &F = ((ScalarEvolutionsImpl*)Impl)->F;
2873 LoopInfo &LI = ((ScalarEvolutionsImpl*)Impl)->LI;
2874
2875 OS << "Classifying expressions for: " << F.getName() << "\n";
2876 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
2877 if (I->getType()->isInteger()) {
2878 OS << *I;
2879 OS << " --> ";
2880 SCEVHandle SV = getSCEV(&*I);
2881 SV->print(OS);
2882 OS << "\t\t";
2883
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002884 if (const Loop *L = LI.getLoopFor((*I).getParent())) {
2885 OS << "Exits: ";
2886 SCEVHandle ExitValue = getSCEVAtScope(&*I, L->getParentLoop());
2887 if (isa<SCEVCouldNotCompute>(ExitValue)) {
2888 OS << "<<Unknown>>";
2889 } else {
2890 OS << *ExitValue;
2891 }
2892 }
2893
2894
2895 OS << "\n";
2896 }
2897
2898 OS << "Determining loop execution counts for: " << F.getName() << "\n";
2899 for (LoopInfo::iterator I = LI.begin(), E = LI.end(); I != E; ++I)
2900 PrintLoopInfo(OS, this, *I);
2901}