blob: ae3d10033f162f87c44419055def51db0ecf9bba [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
120/// getValueRange - Return the tightest constant bounds that this value is
121/// known to have. This method is only valid on integer SCEV objects.
122ConstantRange SCEV::getValueRange() const {
123 const Type *Ty = getType();
124 assert(Ty->isInteger() && "Can't get range for a non-integer SCEV!");
125 // Default to a full range if no better information is available.
126 return ConstantRange(getBitWidth());
127}
128
129uint32_t SCEV::getBitWidth() const {
130 if (const IntegerType* ITy = dyn_cast<IntegerType>(getType()))
131 return ITy->getBitWidth();
132 return 0;
133}
134
135
136SCEVCouldNotCompute::SCEVCouldNotCompute() : SCEV(scCouldNotCompute) {}
137
138bool SCEVCouldNotCompute::isLoopInvariant(const Loop *L) const {
139 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
140 return false;
141}
142
143const Type *SCEVCouldNotCompute::getType() const {
144 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
145 return 0;
146}
147
148bool SCEVCouldNotCompute::hasComputableLoopEvolution(const Loop *L) const {
149 assert(0 && "Attempt to use a SCEVCouldNotCompute object!");
150 return false;
151}
152
153SCEVHandle SCEVCouldNotCompute::
154replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
Dan Gohman89f85052007-10-22 18:31:58 +0000155 const SCEVHandle &Conc,
156 ScalarEvolution &SE) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000157 return this;
158}
159
160void SCEVCouldNotCompute::print(std::ostream &OS) const {
161 OS << "***COULDNOTCOMPUTE***";
162}
163
164bool SCEVCouldNotCompute::classof(const SCEV *S) {
165 return S->getSCEVType() == scCouldNotCompute;
166}
167
168
169// SCEVConstants - Only allow the creation of one SCEVConstant for any
170// particular value. Don't use a SCEVHandle here, or else the object will
171// never be deleted!
172static ManagedStatic<std::map<ConstantInt*, SCEVConstant*> > SCEVConstants;
173
174
175SCEVConstant::~SCEVConstant() {
176 SCEVConstants->erase(V);
177}
178
Dan Gohman89f85052007-10-22 18:31:58 +0000179SCEVHandle ScalarEvolution::getConstant(ConstantInt *V) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000180 SCEVConstant *&R = (*SCEVConstants)[V];
181 if (R == 0) R = new SCEVConstant(V);
182 return R;
183}
184
Dan Gohman89f85052007-10-22 18:31:58 +0000185SCEVHandle ScalarEvolution::getConstant(const APInt& Val) {
186 return getConstant(ConstantInt::get(Val));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000187}
188
189ConstantRange SCEVConstant::getValueRange() const {
190 return ConstantRange(V->getValue());
191}
192
193const Type *SCEVConstant::getType() const { return V->getType(); }
194
195void SCEVConstant::print(std::ostream &OS) const {
196 WriteAsOperand(OS, V, false);
197}
198
199// SCEVTruncates - Only allow the creation of one SCEVTruncateExpr for any
200// particular input. Don't use a SCEVHandle here, or else the object will
201// never be deleted!
202static ManagedStatic<std::map<std::pair<SCEV*, const Type*>,
203 SCEVTruncateExpr*> > SCEVTruncates;
204
205SCEVTruncateExpr::SCEVTruncateExpr(const SCEVHandle &op, const Type *ty)
206 : SCEV(scTruncate), Op(op), Ty(ty) {
207 assert(Op->getType()->isInteger() && Ty->isInteger() &&
208 "Cannot truncate non-integer value!");
209 assert(Op->getType()->getPrimitiveSizeInBits() > Ty->getPrimitiveSizeInBits()
210 && "This is not a truncating conversion!");
211}
212
213SCEVTruncateExpr::~SCEVTruncateExpr() {
214 SCEVTruncates->erase(std::make_pair(Op, Ty));
215}
216
217ConstantRange SCEVTruncateExpr::getValueRange() const {
218 return getOperand()->getValueRange().truncate(getBitWidth());
219}
220
221void SCEVTruncateExpr::print(std::ostream &OS) const {
222 OS << "(truncate " << *Op << " to " << *Ty << ")";
223}
224
225// SCEVZeroExtends - Only allow the creation of one SCEVZeroExtendExpr for any
226// particular input. Don't use a SCEVHandle here, or else the object will never
227// be deleted!
228static ManagedStatic<std::map<std::pair<SCEV*, const Type*>,
229 SCEVZeroExtendExpr*> > SCEVZeroExtends;
230
231SCEVZeroExtendExpr::SCEVZeroExtendExpr(const SCEVHandle &op, const Type *ty)
232 : SCEV(scZeroExtend), Op(op), Ty(ty) {
233 assert(Op->getType()->isInteger() && Ty->isInteger() &&
234 "Cannot zero extend non-integer value!");
235 assert(Op->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits()
236 && "This is not an extending conversion!");
237}
238
239SCEVZeroExtendExpr::~SCEVZeroExtendExpr() {
240 SCEVZeroExtends->erase(std::make_pair(Op, Ty));
241}
242
243ConstantRange SCEVZeroExtendExpr::getValueRange() const {
244 return getOperand()->getValueRange().zeroExtend(getBitWidth());
245}
246
247void SCEVZeroExtendExpr::print(std::ostream &OS) const {
248 OS << "(zeroextend " << *Op << " to " << *Ty << ")";
249}
250
251// SCEVSignExtends - Only allow the creation of one SCEVSignExtendExpr for any
252// particular input. Don't use a SCEVHandle here, or else the object will never
253// be deleted!
254static ManagedStatic<std::map<std::pair<SCEV*, const Type*>,
255 SCEVSignExtendExpr*> > SCEVSignExtends;
256
257SCEVSignExtendExpr::SCEVSignExtendExpr(const SCEVHandle &op, const Type *ty)
258 : SCEV(scSignExtend), Op(op), Ty(ty) {
259 assert(Op->getType()->isInteger() && Ty->isInteger() &&
260 "Cannot sign extend non-integer value!");
261 assert(Op->getType()->getPrimitiveSizeInBits() < Ty->getPrimitiveSizeInBits()
262 && "This is not an extending conversion!");
263}
264
265SCEVSignExtendExpr::~SCEVSignExtendExpr() {
266 SCEVSignExtends->erase(std::make_pair(Op, Ty));
267}
268
269ConstantRange SCEVSignExtendExpr::getValueRange() const {
270 return getOperand()->getValueRange().signExtend(getBitWidth());
271}
272
273void SCEVSignExtendExpr::print(std::ostream &OS) const {
274 OS << "(signextend " << *Op << " to " << *Ty << ")";
275}
276
277// SCEVCommExprs - Only allow the creation of one SCEVCommutativeExpr for any
278// particular input. Don't use a SCEVHandle here, or else the object will never
279// be deleted!
280static ManagedStatic<std::map<std::pair<unsigned, std::vector<SCEV*> >,
281 SCEVCommutativeExpr*> > SCEVCommExprs;
282
283SCEVCommutativeExpr::~SCEVCommutativeExpr() {
284 SCEVCommExprs->erase(std::make_pair(getSCEVType(),
285 std::vector<SCEV*>(Operands.begin(),
286 Operands.end())));
287}
288
289void SCEVCommutativeExpr::print(std::ostream &OS) const {
290 assert(Operands.size() > 1 && "This plus expr shouldn't exist!");
291 const char *OpStr = getOperationStr();
292 OS << "(" << *Operands[0];
293 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
294 OS << OpStr << *Operands[i];
295 OS << ")";
296}
297
298SCEVHandle SCEVCommutativeExpr::
299replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
Dan Gohman89f85052007-10-22 18:31:58 +0000300 const SCEVHandle &Conc,
301 ScalarEvolution &SE) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000302 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
Dan Gohman89f85052007-10-22 18:31:58 +0000303 SCEVHandle H =
304 getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000305 if (H != getOperand(i)) {
306 std::vector<SCEVHandle> NewOps;
307 NewOps.reserve(getNumOperands());
308 for (unsigned j = 0; j != i; ++j)
309 NewOps.push_back(getOperand(j));
310 NewOps.push_back(H);
311 for (++i; i != e; ++i)
312 NewOps.push_back(getOperand(i)->
Dan Gohman89f85052007-10-22 18:31:58 +0000313 replaceSymbolicValuesWithConcrete(Sym, Conc, SE));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000314
315 if (isa<SCEVAddExpr>(this))
Dan Gohman89f85052007-10-22 18:31:58 +0000316 return SE.getAddExpr(NewOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000317 else if (isa<SCEVMulExpr>(this))
Dan Gohman89f85052007-10-22 18:31:58 +0000318 return SE.getMulExpr(NewOps);
Nick Lewycky711640a2007-11-25 22:41:31 +0000319 else if (isa<SCEVSMaxExpr>(this))
320 return SE.getSMaxExpr(NewOps);
Nick Lewyckye7a24ff2008-02-20 06:48:22 +0000321 else if (isa<SCEVUMaxExpr>(this))
322 return SE.getUMaxExpr(NewOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000323 else
324 assert(0 && "Unknown commutative expr!");
325 }
326 }
327 return this;
328}
329
330
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000331// SCEVUDivs - Only allow the creation of one SCEVUDivExpr for any particular
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000332// input. Don't use a SCEVHandle here, or else the object will never be
333// deleted!
334static ManagedStatic<std::map<std::pair<SCEV*, SCEV*>,
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000335 SCEVUDivExpr*> > SCEVUDivs;
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000336
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000337SCEVUDivExpr::~SCEVUDivExpr() {
338 SCEVUDivs->erase(std::make_pair(LHS, RHS));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000339}
340
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000341void SCEVUDivExpr::print(std::ostream &OS) const {
342 OS << "(" << *LHS << " /u " << *RHS << ")";
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000343}
344
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000345const Type *SCEVUDivExpr::getType() const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000346 return LHS->getType();
347}
348
349// SCEVAddRecExprs - Only allow the creation of one SCEVAddRecExpr for any
350// particular input. Don't use a SCEVHandle here, or else the object will never
351// be deleted!
352static ManagedStatic<std::map<std::pair<const Loop *, std::vector<SCEV*> >,
353 SCEVAddRecExpr*> > SCEVAddRecExprs;
354
355SCEVAddRecExpr::~SCEVAddRecExpr() {
356 SCEVAddRecExprs->erase(std::make_pair(L,
357 std::vector<SCEV*>(Operands.begin(),
358 Operands.end())));
359}
360
361SCEVHandle SCEVAddRecExpr::
362replaceSymbolicValuesWithConcrete(const SCEVHandle &Sym,
Dan Gohman89f85052007-10-22 18:31:58 +0000363 const SCEVHandle &Conc,
364 ScalarEvolution &SE) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000365 for (unsigned i = 0, e = getNumOperands(); i != e; ++i) {
Dan Gohman89f85052007-10-22 18:31:58 +0000366 SCEVHandle H =
367 getOperand(i)->replaceSymbolicValuesWithConcrete(Sym, Conc, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000368 if (H != getOperand(i)) {
369 std::vector<SCEVHandle> NewOps;
370 NewOps.reserve(getNumOperands());
371 for (unsigned j = 0; j != i; ++j)
372 NewOps.push_back(getOperand(j));
373 NewOps.push_back(H);
374 for (++i; i != e; ++i)
375 NewOps.push_back(getOperand(i)->
Dan Gohman89f85052007-10-22 18:31:58 +0000376 replaceSymbolicValuesWithConcrete(Sym, Conc, SE));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000377
Dan Gohman89f85052007-10-22 18:31:58 +0000378 return SE.getAddRecExpr(NewOps, L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000379 }
380 }
381 return this;
382}
383
384
385bool SCEVAddRecExpr::isLoopInvariant(const Loop *QueryLoop) const {
386 // This recurrence is invariant w.r.t to QueryLoop iff QueryLoop doesn't
387 // contain L and if the start is invariant.
388 return !QueryLoop->contains(L->getHeader()) &&
389 getOperand(0)->isLoopInvariant(QueryLoop);
390}
391
392
393void SCEVAddRecExpr::print(std::ostream &OS) const {
394 OS << "{" << *Operands[0];
395 for (unsigned i = 1, e = Operands.size(); i != e; ++i)
396 OS << ",+," << *Operands[i];
397 OS << "}<" << L->getHeader()->getName() + ">";
398}
399
400// SCEVUnknowns - Only allow the creation of one SCEVUnknown for any particular
401// value. Don't use a SCEVHandle here, or else the object will never be
402// deleted!
403static ManagedStatic<std::map<Value*, SCEVUnknown*> > SCEVUnknowns;
404
405SCEVUnknown::~SCEVUnknown() { SCEVUnknowns->erase(V); }
406
407bool SCEVUnknown::isLoopInvariant(const Loop *L) const {
408 // All non-instruction values are loop invariant. All instructions are loop
409 // invariant if they are not contained in the specified loop.
410 if (Instruction *I = dyn_cast<Instruction>(V))
411 return !L->contains(I->getParent());
412 return true;
413}
414
415const Type *SCEVUnknown::getType() const {
416 return V->getType();
417}
418
419void SCEVUnknown::print(std::ostream &OS) const {
420 WriteAsOperand(OS, V, false);
421}
422
423//===----------------------------------------------------------------------===//
424// SCEV Utilities
425//===----------------------------------------------------------------------===//
426
427namespace {
428 /// SCEVComplexityCompare - Return true if the complexity of the LHS is less
429 /// than the complexity of the RHS. This comparator is used to canonicalize
430 /// expressions.
431 struct VISIBILITY_HIDDEN SCEVComplexityCompare {
Dan Gohmanc0c69cf2008-04-14 18:23:56 +0000432 bool operator()(const SCEV *LHS, const SCEV *RHS) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000433 return LHS->getSCEVType() < RHS->getSCEVType();
434 }
435 };
436}
437
438/// GroupByComplexity - Given a list of SCEV objects, order them by their
439/// complexity, and group objects of the same complexity together by value.
440/// When this routine is finished, we know that any duplicates in the vector are
441/// consecutive and that complexity is monotonically increasing.
442///
443/// Note that we go take special precautions to ensure that we get determinstic
444/// results from this routine. In other words, we don't want the results of
445/// this to depend on where the addresses of various SCEV objects happened to
446/// land in memory.
447///
448static void GroupByComplexity(std::vector<SCEVHandle> &Ops) {
449 if (Ops.size() < 2) return; // Noop
450 if (Ops.size() == 2) {
451 // This is the common case, which also happens to be trivially simple.
452 // Special case it.
Dan Gohmanc0c69cf2008-04-14 18:23:56 +0000453 if (SCEVComplexityCompare()(Ops[1], Ops[0]))
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000454 std::swap(Ops[0], Ops[1]);
455 return;
456 }
457
458 // Do the rough sort by complexity.
459 std::sort(Ops.begin(), Ops.end(), SCEVComplexityCompare());
460
461 // Now that we are sorted by complexity, group elements of the same
462 // complexity. Note that this is, at worst, N^2, but the vector is likely to
463 // be extremely short in practice. Note that we take this approach because we
464 // do not want to depend on the addresses of the objects we are grouping.
465 for (unsigned i = 0, e = Ops.size(); i != e-2; ++i) {
466 SCEV *S = Ops[i];
467 unsigned Complexity = S->getSCEVType();
468
469 // If there are any objects of the same complexity and same value as this
470 // one, group them.
471 for (unsigned j = i+1; j != e && Ops[j]->getSCEVType() == Complexity; ++j) {
472 if (Ops[j] == S) { // Found a duplicate.
473 // Move it to immediately after i'th element.
474 std::swap(Ops[i+1], Ops[j]);
475 ++i; // no need to rescan it.
476 if (i == e-2) return; // Done!
477 }
478 }
479 }
480}
481
482
483
484//===----------------------------------------------------------------------===//
485// Simple SCEV method implementations
486//===----------------------------------------------------------------------===//
487
488/// getIntegerSCEV - Given an integer or FP type, create a constant for the
489/// specified signed integer value and return a SCEV for the constant.
Dan Gohman89f85052007-10-22 18:31:58 +0000490SCEVHandle ScalarEvolution::getIntegerSCEV(int Val, const Type *Ty) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000491 Constant *C;
492 if (Val == 0)
493 C = Constant::getNullValue(Ty);
494 else if (Ty->isFloatingPoint())
Chris Lattner5e0610f2008-04-20 00:41:09 +0000495 C = ConstantFP::get(APFloat(Ty==Type::FloatTy ? APFloat::IEEEsingle :
496 APFloat::IEEEdouble, Val));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000497 else
498 C = ConstantInt::get(Ty, Val);
Dan Gohman89f85052007-10-22 18:31:58 +0000499 return getUnknown(C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000500}
501
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000502/// getNegativeSCEV - Return a SCEV corresponding to -V = -1*V
503///
Dan Gohman89f85052007-10-22 18:31:58 +0000504SCEVHandle ScalarEvolution::getNegativeSCEV(const SCEVHandle &V) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000505 if (SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
Dan Gohman89f85052007-10-22 18:31:58 +0000506 return getUnknown(ConstantExpr::getNeg(VC->getValue()));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000507
Nick Lewycky0cf58682008-02-20 06:58:55 +0000508 return getMulExpr(V, getConstant(ConstantInt::getAllOnesValue(V->getType())));
Nick Lewyckye7a24ff2008-02-20 06:48:22 +0000509}
510
511/// getNotSCEV - Return a SCEV corresponding to ~V = -1-V
512SCEVHandle ScalarEvolution::getNotSCEV(const SCEVHandle &V) {
513 if (SCEVConstant *VC = dyn_cast<SCEVConstant>(V))
514 return getUnknown(ConstantExpr::getNot(VC->getValue()));
515
Nick Lewycky0cf58682008-02-20 06:58:55 +0000516 SCEVHandle AllOnes = getConstant(ConstantInt::getAllOnesValue(V->getType()));
Nick Lewyckye7a24ff2008-02-20 06:48:22 +0000517 return getMinusSCEV(AllOnes, V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000518}
519
520/// getMinusSCEV - Return a SCEV corresponding to LHS - RHS.
521///
Dan Gohman89f85052007-10-22 18:31:58 +0000522SCEVHandle ScalarEvolution::getMinusSCEV(const SCEVHandle &LHS,
523 const SCEVHandle &RHS) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000524 // X - Y --> X + -Y
Dan Gohman89f85052007-10-22 18:31:58 +0000525 return getAddExpr(LHS, getNegativeSCEV(RHS));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000526}
527
528
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000529/// BinomialCoefficient - Compute BC(It, K). The result is of the same type as
530/// It. Assume, K > 0.
531static SCEVHandle BinomialCoefficient(SCEVHandle It, unsigned K,
532 ScalarEvolution &SE) {
533 // We are using the following formula for BC(It, K):
534 //
535 // BC(It, K) = (It * (It - 1) * ... * (It - K + 1)) / K!
536 //
537 // Suppose, W is the bitwidth of It (and of the return value as well). We
538 // must be prepared for overflow. Hence, we must assure that the result of
539 // our computation is equal to the accurate one modulo 2^W. Unfortunately,
540 // division isn't safe in modular arithmetic. This means we must perform the
541 // whole computation accurately and then truncate the result to W bits.
542 //
543 // The dividend of the formula is a multiplication of K integers of bitwidth
544 // W. K*W bits suffice to compute it accurately.
545 //
546 // FIXME: We assume the divisor can be accurately computed using 16-bit
547 // unsigned integer type. It is true up to K = 8 (AddRecs of length 9). In
548 // future we may use APInt to use the minimum number of bits necessary to
549 // compute it accurately.
550 //
551 // It is safe to use unsigned division here: the dividend is nonnegative and
552 // the divisor is positive.
553
554 // Handle the simplest case efficiently.
555 if (K == 1)
556 return It;
557
558 assert(K < 9 && "We cannot handle such long AddRecs yet.");
559
560 // FIXME: A temporary hack to remove in future. Arbitrary precision integers
561 // aren't supported by the code generator yet. For the dividend, the bitwidth
562 // we use is the smallest power of 2 greater or equal to K*W and less or equal
563 // to 64. Note that setting the upper bound for bitwidth may still lead to
564 // miscompilation in some cases.
565 unsigned DividendBits = 1U << Log2_32_Ceil(K * It->getBitWidth());
566 if (DividendBits > 64)
567 DividendBits = 64;
568#if 0 // Waiting for the APInt support in the code generator...
569 unsigned DividendBits = K * It->getBitWidth();
570#endif
571
572 const IntegerType *DividendTy = IntegerType::get(DividendBits);
Nick Lewyckydbaa60a2008-06-13 04:38:55 +0000573 const SCEVHandle ExIt = SE.getTruncateOrZeroExtend(It, DividendTy);
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000574
575 // The final number of bits we need to perform the division is the maximum of
576 // dividend and divisor bitwidths.
577 const IntegerType *DivisionTy =
578 IntegerType::get(std::max(DividendBits, 16U));
579
580 // Compute K! We know K >= 2 here.
581 unsigned F = 2;
582 for (unsigned i = 3; i <= K; ++i)
583 F *= i;
584 APInt Divisor(DivisionTy->getBitWidth(), F);
585
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000586 // Handle this case efficiently, it is common to have constant iteration
587 // counts while computing loop exit values.
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000588 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(ExIt)) {
589 const APInt& N = SC->getValue()->getValue();
590 APInt Dividend(N.getBitWidth(), 1);
591 for (; K; --K)
592 Dividend *= N-(K-1);
593 if (DividendTy != DivisionTy)
594 Dividend = Dividend.zext(DivisionTy->getBitWidth());
Nick Lewyckydbaa60a2008-06-13 04:38:55 +0000595
596 APInt Result = Dividend.udiv(Divisor);
597 if (Result.getBitWidth() != It->getBitWidth())
598 Result = Result.trunc(It->getBitWidth());
599
600 return SE.getConstant(Result);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000601 }
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000602
603 SCEVHandle Dividend = ExIt;
604 for (unsigned i = 1; i != K; ++i)
605 Dividend =
606 SE.getMulExpr(Dividend,
607 SE.getMinusSCEV(ExIt, SE.getIntegerSCEV(i, DividendTy)));
Nick Lewyckydbaa60a2008-06-13 04:38:55 +0000608
609 return SE.getTruncateOrZeroExtend(
610 SE.getUDivExpr(
611 SE.getTruncateOrZeroExtend(Dividend, DivisionTy),
612 SE.getConstant(Divisor)
613 ), It->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000614}
615
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000616/// evaluateAtIteration - Return the value of this chain of recurrences at
617/// the specified iteration number. We can evaluate this recurrence by
618/// multiplying each element in the chain by the binomial coefficient
619/// corresponding to it. In other words, we can evaluate {A,+,B,+,C,+,D} as:
620///
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000621/// A*BC(It, 0) + B*BC(It, 1) + C*BC(It, 2) + D*BC(It, 3)
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000622///
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000623/// where BC(It, k) stands for binomial coefficient.
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000624///
Dan Gohman89f85052007-10-22 18:31:58 +0000625SCEVHandle SCEVAddRecExpr::evaluateAtIteration(SCEVHandle It,
626 ScalarEvolution &SE) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000627 SCEVHandle Result = getStart();
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000628 for (unsigned i = 1, e = getNumOperands(); i != e; ++i) {
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +0000629 // The computation is correct in the face of overflow provided that the
630 // multiplication is performed _after_ the evaluation of the binomial
631 // coefficient.
632 SCEVHandle Val = SE.getMulExpr(getOperand(i),
633 BinomialCoefficient(It, i, SE));
Dan Gohman89f85052007-10-22 18:31:58 +0000634 Result = SE.getAddExpr(Result, Val);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000635 }
636 return Result;
637}
638
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000639//===----------------------------------------------------------------------===//
640// SCEV Expression folder implementations
641//===----------------------------------------------------------------------===//
642
Dan Gohman89f85052007-10-22 18:31:58 +0000643SCEVHandle ScalarEvolution::getTruncateExpr(const SCEVHandle &Op, const Type *Ty) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000644 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
Dan Gohman89f85052007-10-22 18:31:58 +0000645 return getUnknown(
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000646 ConstantExpr::getTrunc(SC->getValue(), Ty));
647
648 // If the input value is a chrec scev made out of constants, truncate
649 // all of the constants.
650 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(Op)) {
651 std::vector<SCEVHandle> Operands;
652 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
653 // FIXME: This should allow truncation of other expression types!
654 if (isa<SCEVConstant>(AddRec->getOperand(i)))
Dan Gohman89f85052007-10-22 18:31:58 +0000655 Operands.push_back(getTruncateExpr(AddRec->getOperand(i), Ty));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000656 else
657 break;
658 if (Operands.size() == AddRec->getNumOperands())
Dan Gohman89f85052007-10-22 18:31:58 +0000659 return getAddRecExpr(Operands, AddRec->getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000660 }
661
662 SCEVTruncateExpr *&Result = (*SCEVTruncates)[std::make_pair(Op, Ty)];
663 if (Result == 0) Result = new SCEVTruncateExpr(Op, Ty);
664 return Result;
665}
666
Dan Gohman89f85052007-10-22 18:31:58 +0000667SCEVHandle ScalarEvolution::getZeroExtendExpr(const SCEVHandle &Op, const Type *Ty) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000668 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
Dan Gohman89f85052007-10-22 18:31:58 +0000669 return getUnknown(
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000670 ConstantExpr::getZExt(SC->getValue(), Ty));
671
672 // FIXME: If the input value is a chrec scev, and we can prove that the value
673 // did not overflow the old, smaller, value, we can zero extend all of the
674 // operands (often constants). This would allow analysis of something like
675 // this: for (unsigned char X = 0; X < 100; ++X) { int Y = X; }
676
677 SCEVZeroExtendExpr *&Result = (*SCEVZeroExtends)[std::make_pair(Op, Ty)];
678 if (Result == 0) Result = new SCEVZeroExtendExpr(Op, Ty);
679 return Result;
680}
681
Dan Gohman89f85052007-10-22 18:31:58 +0000682SCEVHandle ScalarEvolution::getSignExtendExpr(const SCEVHandle &Op, const Type *Ty) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000683 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(Op))
Dan Gohman89f85052007-10-22 18:31:58 +0000684 return getUnknown(
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000685 ConstantExpr::getSExt(SC->getValue(), Ty));
686
687 // FIXME: If the input value is a chrec scev, and we can prove that the value
688 // did not overflow the old, smaller, value, we can sign extend all of the
689 // operands (often constants). This would allow analysis of something like
690 // this: for (signed char X = 0; X < 100; ++X) { int Y = X; }
691
692 SCEVSignExtendExpr *&Result = (*SCEVSignExtends)[std::make_pair(Op, Ty)];
693 if (Result == 0) Result = new SCEVSignExtendExpr(Op, Ty);
694 return Result;
695}
696
Nick Lewyckydbaa60a2008-06-13 04:38:55 +0000697/// getTruncateOrZeroExtend - Return a SCEV corresponding to a conversion
698/// of the input value to the specified type. If the type must be
699/// extended, it is zero extended.
700SCEVHandle ScalarEvolution::getTruncateOrZeroExtend(const SCEVHandle &V,
701 const Type *Ty) {
702 const Type *SrcTy = V->getType();
703 assert(SrcTy->isInteger() && Ty->isInteger() &&
704 "Cannot truncate or zero extend with non-integer arguments!");
705 if (SrcTy->getPrimitiveSizeInBits() == Ty->getPrimitiveSizeInBits())
706 return V; // No conversion
707 if (SrcTy->getPrimitiveSizeInBits() > Ty->getPrimitiveSizeInBits())
708 return getTruncateExpr(V, Ty);
709 return getZeroExtendExpr(V, Ty);
710}
711
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000712// get - Get a canonical add expression, or something simpler if possible.
Dan Gohman89f85052007-10-22 18:31:58 +0000713SCEVHandle ScalarEvolution::getAddExpr(std::vector<SCEVHandle> &Ops) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000714 assert(!Ops.empty() && "Cannot get empty add!");
715 if (Ops.size() == 1) return Ops[0];
716
717 // Sort by complexity, this groups all similar expression types together.
718 GroupByComplexity(Ops);
719
720 // If there are any constants, fold them together.
721 unsigned Idx = 0;
722 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
723 ++Idx;
724 assert(Idx < Ops.size());
725 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
726 // We found two constants, fold them together!
Nick Lewyckye7a24ff2008-02-20 06:48:22 +0000727 ConstantInt *Fold = ConstantInt::get(LHSC->getValue()->getValue() +
728 RHSC->getValue()->getValue());
729 Ops[0] = getConstant(Fold);
730 Ops.erase(Ops.begin()+1); // Erase the folded element
731 if (Ops.size() == 1) return Ops[0];
732 LHSC = cast<SCEVConstant>(Ops[0]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000733 }
734
735 // If we are left with a constant zero being added, strip it off.
736 if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
737 Ops.erase(Ops.begin());
738 --Idx;
739 }
740 }
741
742 if (Ops.size() == 1) return Ops[0];
743
744 // Okay, check to see if the same value occurs in the operand list twice. If
745 // so, merge them together into an multiply expression. Since we sorted the
746 // list, these values are required to be adjacent.
747 const Type *Ty = Ops[0]->getType();
748 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
749 if (Ops[i] == Ops[i+1]) { // X + Y + Y --> X + Y*2
750 // Found a match, merge the two values into a multiply, and add any
751 // remaining values to the result.
Dan Gohman89f85052007-10-22 18:31:58 +0000752 SCEVHandle Two = getIntegerSCEV(2, Ty);
753 SCEVHandle Mul = getMulExpr(Ops[i], Two);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000754 if (Ops.size() == 2)
755 return Mul;
756 Ops.erase(Ops.begin()+i, Ops.begin()+i+2);
757 Ops.push_back(Mul);
Dan Gohman89f85052007-10-22 18:31:58 +0000758 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000759 }
760
761 // Now we know the first non-constant operand. Skip past any cast SCEVs.
762 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddExpr)
763 ++Idx;
764
765 // If there are add operands they would be next.
766 if (Idx < Ops.size()) {
767 bool DeletedAdd = false;
768 while (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[Idx])) {
769 // If we have an add, expand the add operands onto the end of the operands
770 // list.
771 Ops.insert(Ops.end(), Add->op_begin(), Add->op_end());
772 Ops.erase(Ops.begin()+Idx);
773 DeletedAdd = true;
774 }
775
776 // If we deleted at least one add, we added operands to the end of the list,
777 // and they are not necessarily sorted. Recurse to resort and resimplify
778 // any operands we just aquired.
779 if (DeletedAdd)
Dan Gohman89f85052007-10-22 18:31:58 +0000780 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000781 }
782
783 // Skip over the add expression until we get to a multiply.
784 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
785 ++Idx;
786
787 // If we are adding something to a multiply expression, make sure the
788 // something is not already an operand of the multiply. If so, merge it into
789 // the multiply.
790 for (; Idx < Ops.size() && isa<SCEVMulExpr>(Ops[Idx]); ++Idx) {
791 SCEVMulExpr *Mul = cast<SCEVMulExpr>(Ops[Idx]);
792 for (unsigned MulOp = 0, e = Mul->getNumOperands(); MulOp != e; ++MulOp) {
793 SCEV *MulOpSCEV = Mul->getOperand(MulOp);
794 for (unsigned AddOp = 0, e = Ops.size(); AddOp != e; ++AddOp)
795 if (MulOpSCEV == Ops[AddOp] && !isa<SCEVConstant>(MulOpSCEV)) {
796 // Fold W + X + (X * Y * Z) --> W + (X * ((Y*Z)+1))
797 SCEVHandle InnerMul = Mul->getOperand(MulOp == 0);
798 if (Mul->getNumOperands() != 2) {
799 // If the multiply has more than two operands, we must get the
800 // Y*Z term.
801 std::vector<SCEVHandle> MulOps(Mul->op_begin(), Mul->op_end());
802 MulOps.erase(MulOps.begin()+MulOp);
Dan Gohman89f85052007-10-22 18:31:58 +0000803 InnerMul = getMulExpr(MulOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000804 }
Dan Gohman89f85052007-10-22 18:31:58 +0000805 SCEVHandle One = getIntegerSCEV(1, Ty);
806 SCEVHandle AddOne = getAddExpr(InnerMul, One);
807 SCEVHandle OuterMul = getMulExpr(AddOne, Ops[AddOp]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000808 if (Ops.size() == 2) return OuterMul;
809 if (AddOp < Idx) {
810 Ops.erase(Ops.begin()+AddOp);
811 Ops.erase(Ops.begin()+Idx-1);
812 } else {
813 Ops.erase(Ops.begin()+Idx);
814 Ops.erase(Ops.begin()+AddOp-1);
815 }
816 Ops.push_back(OuterMul);
Dan Gohman89f85052007-10-22 18:31:58 +0000817 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000818 }
819
820 // Check this multiply against other multiplies being added together.
821 for (unsigned OtherMulIdx = Idx+1;
822 OtherMulIdx < Ops.size() && isa<SCEVMulExpr>(Ops[OtherMulIdx]);
823 ++OtherMulIdx) {
824 SCEVMulExpr *OtherMul = cast<SCEVMulExpr>(Ops[OtherMulIdx]);
825 // If MulOp occurs in OtherMul, we can fold the two multiplies
826 // together.
827 for (unsigned OMulOp = 0, e = OtherMul->getNumOperands();
828 OMulOp != e; ++OMulOp)
829 if (OtherMul->getOperand(OMulOp) == MulOpSCEV) {
830 // Fold X + (A*B*C) + (A*D*E) --> X + (A*(B*C+D*E))
831 SCEVHandle InnerMul1 = Mul->getOperand(MulOp == 0);
832 if (Mul->getNumOperands() != 2) {
833 std::vector<SCEVHandle> MulOps(Mul->op_begin(), Mul->op_end());
834 MulOps.erase(MulOps.begin()+MulOp);
Dan Gohman89f85052007-10-22 18:31:58 +0000835 InnerMul1 = getMulExpr(MulOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000836 }
837 SCEVHandle InnerMul2 = OtherMul->getOperand(OMulOp == 0);
838 if (OtherMul->getNumOperands() != 2) {
839 std::vector<SCEVHandle> MulOps(OtherMul->op_begin(),
840 OtherMul->op_end());
841 MulOps.erase(MulOps.begin()+OMulOp);
Dan Gohman89f85052007-10-22 18:31:58 +0000842 InnerMul2 = getMulExpr(MulOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000843 }
Dan Gohman89f85052007-10-22 18:31:58 +0000844 SCEVHandle InnerMulSum = getAddExpr(InnerMul1,InnerMul2);
845 SCEVHandle OuterMul = getMulExpr(MulOpSCEV, InnerMulSum);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000846 if (Ops.size() == 2) return OuterMul;
847 Ops.erase(Ops.begin()+Idx);
848 Ops.erase(Ops.begin()+OtherMulIdx-1);
849 Ops.push_back(OuterMul);
Dan Gohman89f85052007-10-22 18:31:58 +0000850 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000851 }
852 }
853 }
854 }
855
856 // If there are any add recurrences in the operands list, see if any other
857 // added values are loop invariant. If so, we can fold them into the
858 // recurrence.
859 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
860 ++Idx;
861
862 // Scan over all recurrences, trying to fold loop invariants into them.
863 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
864 // Scan all of the other operands to this add and add them to the vector if
865 // they are loop invariant w.r.t. the recurrence.
866 std::vector<SCEVHandle> LIOps;
867 SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
868 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
869 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
870 LIOps.push_back(Ops[i]);
871 Ops.erase(Ops.begin()+i);
872 --i; --e;
873 }
874
875 // If we found some loop invariants, fold them into the recurrence.
876 if (!LIOps.empty()) {
877 // NLI + LI + { Start,+,Step} --> NLI + { LI+Start,+,Step }
878 LIOps.push_back(AddRec->getStart());
879
880 std::vector<SCEVHandle> AddRecOps(AddRec->op_begin(), AddRec->op_end());
Dan Gohman89f85052007-10-22 18:31:58 +0000881 AddRecOps[0] = getAddExpr(LIOps);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000882
Dan Gohman89f85052007-10-22 18:31:58 +0000883 SCEVHandle NewRec = getAddRecExpr(AddRecOps, AddRec->getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000884 // If all of the other operands were loop invariant, we are done.
885 if (Ops.size() == 1) return NewRec;
886
887 // Otherwise, add the folded AddRec by the non-liv parts.
888 for (unsigned i = 0;; ++i)
889 if (Ops[i] == AddRec) {
890 Ops[i] = NewRec;
891 break;
892 }
Dan Gohman89f85052007-10-22 18:31:58 +0000893 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000894 }
895
896 // Okay, if there weren't any loop invariants to be folded, check to see if
897 // there are multiple AddRec's with the same loop induction variable being
898 // added together. If so, we can fold them.
899 for (unsigned OtherIdx = Idx+1;
900 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
901 if (OtherIdx != Idx) {
902 SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
903 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
904 // Other + {A,+,B} + {C,+,D} --> Other + {A+C,+,B+D}
905 std::vector<SCEVHandle> NewOps(AddRec->op_begin(), AddRec->op_end());
906 for (unsigned i = 0, e = OtherAddRec->getNumOperands(); i != e; ++i) {
907 if (i >= NewOps.size()) {
908 NewOps.insert(NewOps.end(), OtherAddRec->op_begin()+i,
909 OtherAddRec->op_end());
910 break;
911 }
Dan Gohman89f85052007-10-22 18:31:58 +0000912 NewOps[i] = getAddExpr(NewOps[i], OtherAddRec->getOperand(i));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000913 }
Dan Gohman89f85052007-10-22 18:31:58 +0000914 SCEVHandle NewAddRec = getAddRecExpr(NewOps, AddRec->getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000915
916 if (Ops.size() == 2) return NewAddRec;
917
918 Ops.erase(Ops.begin()+Idx);
919 Ops.erase(Ops.begin()+OtherIdx-1);
920 Ops.push_back(NewAddRec);
Dan Gohman89f85052007-10-22 18:31:58 +0000921 return getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000922 }
923 }
924
925 // Otherwise couldn't fold anything into this recurrence. Move onto the
926 // next one.
927 }
928
929 // Okay, it looks like we really DO need an add expr. Check to see if we
930 // already have one, otherwise create a new one.
931 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
932 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scAddExpr,
933 SCEVOps)];
934 if (Result == 0) Result = new SCEVAddExpr(Ops);
935 return Result;
936}
937
938
Dan Gohman89f85052007-10-22 18:31:58 +0000939SCEVHandle ScalarEvolution::getMulExpr(std::vector<SCEVHandle> &Ops) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000940 assert(!Ops.empty() && "Cannot get empty mul!");
941
942 // Sort by complexity, this groups all similar expression types together.
943 GroupByComplexity(Ops);
944
945 // If there are any constants, fold them together.
946 unsigned Idx = 0;
947 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
948
949 // C1*(C2+V) -> C1*C2 + C1*V
950 if (Ops.size() == 2)
951 if (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(Ops[1]))
952 if (Add->getNumOperands() == 2 &&
953 isa<SCEVConstant>(Add->getOperand(0)))
Dan Gohman89f85052007-10-22 18:31:58 +0000954 return getAddExpr(getMulExpr(LHSC, Add->getOperand(0)),
955 getMulExpr(LHSC, Add->getOperand(1)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000956
957
958 ++Idx;
959 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
960 // We found two constants, fold them together!
Nick Lewyckye7a24ff2008-02-20 06:48:22 +0000961 ConstantInt *Fold = ConstantInt::get(LHSC->getValue()->getValue() *
962 RHSC->getValue()->getValue());
963 Ops[0] = getConstant(Fold);
964 Ops.erase(Ops.begin()+1); // Erase the folded element
965 if (Ops.size() == 1) return Ops[0];
966 LHSC = cast<SCEVConstant>(Ops[0]);
Dan Gohmanf17a25c2007-07-18 16:29:46 +0000967 }
968
969 // If we are left with a constant one being multiplied, strip it off.
970 if (cast<SCEVConstant>(Ops[0])->getValue()->equalsInt(1)) {
971 Ops.erase(Ops.begin());
972 --Idx;
973 } else if (cast<SCEVConstant>(Ops[0])->getValue()->isZero()) {
974 // If we have a multiply of zero, it will always be zero.
975 return Ops[0];
976 }
977 }
978
979 // Skip over the add expression until we get to a multiply.
980 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scMulExpr)
981 ++Idx;
982
983 if (Ops.size() == 1)
984 return Ops[0];
985
986 // If there are mul operands inline them all into this expression.
987 if (Idx < Ops.size()) {
988 bool DeletedMul = false;
989 while (SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(Ops[Idx])) {
990 // If we have an mul, expand the mul operands onto the end of the operands
991 // list.
992 Ops.insert(Ops.end(), Mul->op_begin(), Mul->op_end());
993 Ops.erase(Ops.begin()+Idx);
994 DeletedMul = true;
995 }
996
997 // If we deleted at least one mul, we added operands to the end of the list,
998 // and they are not necessarily sorted. Recurse to resort and resimplify
999 // any operands we just aquired.
1000 if (DeletedMul)
Dan Gohman89f85052007-10-22 18:31:58 +00001001 return getMulExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001002 }
1003
1004 // If there are any add recurrences in the operands list, see if any other
1005 // added values are loop invariant. If so, we can fold them into the
1006 // recurrence.
1007 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scAddRecExpr)
1008 ++Idx;
1009
1010 // Scan over all recurrences, trying to fold loop invariants into them.
1011 for (; Idx < Ops.size() && isa<SCEVAddRecExpr>(Ops[Idx]); ++Idx) {
1012 // Scan all of the other operands to this mul and add them to the vector if
1013 // they are loop invariant w.r.t. the recurrence.
1014 std::vector<SCEVHandle> LIOps;
1015 SCEVAddRecExpr *AddRec = cast<SCEVAddRecExpr>(Ops[Idx]);
1016 for (unsigned i = 0, e = Ops.size(); i != e; ++i)
1017 if (Ops[i]->isLoopInvariant(AddRec->getLoop())) {
1018 LIOps.push_back(Ops[i]);
1019 Ops.erase(Ops.begin()+i);
1020 --i; --e;
1021 }
1022
1023 // If we found some loop invariants, fold them into the recurrence.
1024 if (!LIOps.empty()) {
1025 // NLI * LI * { Start,+,Step} --> NLI * { LI*Start,+,LI*Step }
1026 std::vector<SCEVHandle> NewOps;
1027 NewOps.reserve(AddRec->getNumOperands());
1028 if (LIOps.size() == 1) {
1029 SCEV *Scale = LIOps[0];
1030 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i)
Dan Gohman89f85052007-10-22 18:31:58 +00001031 NewOps.push_back(getMulExpr(Scale, AddRec->getOperand(i)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001032 } else {
1033 for (unsigned i = 0, e = AddRec->getNumOperands(); i != e; ++i) {
1034 std::vector<SCEVHandle> MulOps(LIOps);
1035 MulOps.push_back(AddRec->getOperand(i));
Dan Gohman89f85052007-10-22 18:31:58 +00001036 NewOps.push_back(getMulExpr(MulOps));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001037 }
1038 }
1039
Dan Gohman89f85052007-10-22 18:31:58 +00001040 SCEVHandle NewRec = getAddRecExpr(NewOps, AddRec->getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001041
1042 // If all of the other operands were loop invariant, we are done.
1043 if (Ops.size() == 1) return NewRec;
1044
1045 // Otherwise, multiply the folded AddRec by the non-liv parts.
1046 for (unsigned i = 0;; ++i)
1047 if (Ops[i] == AddRec) {
1048 Ops[i] = NewRec;
1049 break;
1050 }
Dan Gohman89f85052007-10-22 18:31:58 +00001051 return getMulExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001052 }
1053
1054 // Okay, if there weren't any loop invariants to be folded, check to see if
1055 // there are multiple AddRec's with the same loop induction variable being
1056 // multiplied together. If so, we can fold them.
1057 for (unsigned OtherIdx = Idx+1;
1058 OtherIdx < Ops.size() && isa<SCEVAddRecExpr>(Ops[OtherIdx]);++OtherIdx)
1059 if (OtherIdx != Idx) {
1060 SCEVAddRecExpr *OtherAddRec = cast<SCEVAddRecExpr>(Ops[OtherIdx]);
1061 if (AddRec->getLoop() == OtherAddRec->getLoop()) {
1062 // F * G --> {A,+,B} * {C,+,D} --> {A*C,+,F*D + G*B + B*D}
1063 SCEVAddRecExpr *F = AddRec, *G = OtherAddRec;
Dan Gohman89f85052007-10-22 18:31:58 +00001064 SCEVHandle NewStart = getMulExpr(F->getStart(),
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001065 G->getStart());
Dan Gohman89f85052007-10-22 18:31:58 +00001066 SCEVHandle B = F->getStepRecurrence(*this);
1067 SCEVHandle D = G->getStepRecurrence(*this);
1068 SCEVHandle NewStep = getAddExpr(getMulExpr(F, D),
1069 getMulExpr(G, B),
1070 getMulExpr(B, D));
1071 SCEVHandle NewAddRec = getAddRecExpr(NewStart, NewStep,
1072 F->getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001073 if (Ops.size() == 2) return NewAddRec;
1074
1075 Ops.erase(Ops.begin()+Idx);
1076 Ops.erase(Ops.begin()+OtherIdx-1);
1077 Ops.push_back(NewAddRec);
Dan Gohman89f85052007-10-22 18:31:58 +00001078 return getMulExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001079 }
1080 }
1081
1082 // Otherwise couldn't fold anything into this recurrence. Move onto the
1083 // next one.
1084 }
1085
1086 // Okay, it looks like we really DO need an mul expr. Check to see if we
1087 // already have one, otherwise create a new one.
1088 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
1089 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scMulExpr,
1090 SCEVOps)];
1091 if (Result == 0)
1092 Result = new SCEVMulExpr(Ops);
1093 return Result;
1094}
1095
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +00001096SCEVHandle ScalarEvolution::getUDivExpr(const SCEVHandle &LHS, const SCEVHandle &RHS) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001097 if (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS)) {
1098 if (RHSC->getValue()->equalsInt(1))
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +00001099 return LHS; // X udiv 1 --> x
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001100
1101 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(LHS)) {
1102 Constant *LHSCV = LHSC->getValue();
1103 Constant *RHSCV = RHSC->getValue();
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +00001104 return getUnknown(ConstantExpr::getUDiv(LHSCV, RHSCV));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001105 }
1106 }
1107
1108 // FIXME: implement folding of (X*4)/4 when we know X*4 doesn't overflow.
1109
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +00001110 SCEVUDivExpr *&Result = (*SCEVUDivs)[std::make_pair(LHS, RHS)];
1111 if (Result == 0) Result = new SCEVUDivExpr(LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001112 return Result;
1113}
1114
1115
1116/// SCEVAddRecExpr::get - Get a add recurrence expression for the
1117/// specified loop. Simplify the expression as much as possible.
Dan Gohman89f85052007-10-22 18:31:58 +00001118SCEVHandle ScalarEvolution::getAddRecExpr(const SCEVHandle &Start,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001119 const SCEVHandle &Step, const Loop *L) {
1120 std::vector<SCEVHandle> Operands;
1121 Operands.push_back(Start);
1122 if (SCEVAddRecExpr *StepChrec = dyn_cast<SCEVAddRecExpr>(Step))
1123 if (StepChrec->getLoop() == L) {
1124 Operands.insert(Operands.end(), StepChrec->op_begin(),
1125 StepChrec->op_end());
Dan Gohman89f85052007-10-22 18:31:58 +00001126 return getAddRecExpr(Operands, L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001127 }
1128
1129 Operands.push_back(Step);
Dan Gohman89f85052007-10-22 18:31:58 +00001130 return getAddRecExpr(Operands, L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001131}
1132
1133/// SCEVAddRecExpr::get - Get a add recurrence expression for the
1134/// specified loop. Simplify the expression as much as possible.
Dan Gohman89f85052007-10-22 18:31:58 +00001135SCEVHandle ScalarEvolution::getAddRecExpr(std::vector<SCEVHandle> &Operands,
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001136 const Loop *L) {
1137 if (Operands.size() == 1) return Operands[0];
1138
1139 if (SCEVConstant *StepC = dyn_cast<SCEVConstant>(Operands.back()))
1140 if (StepC->getValue()->isZero()) {
1141 Operands.pop_back();
Dan Gohman89f85052007-10-22 18:31:58 +00001142 return getAddRecExpr(Operands, L); // { X,+,0 } --> X
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001143 }
1144
1145 SCEVAddRecExpr *&Result =
1146 (*SCEVAddRecExprs)[std::make_pair(L, std::vector<SCEV*>(Operands.begin(),
1147 Operands.end()))];
1148 if (Result == 0) Result = new SCEVAddRecExpr(Operands, L);
1149 return Result;
1150}
1151
Nick Lewycky711640a2007-11-25 22:41:31 +00001152SCEVHandle ScalarEvolution::getSMaxExpr(const SCEVHandle &LHS,
1153 const SCEVHandle &RHS) {
1154 std::vector<SCEVHandle> Ops;
1155 Ops.push_back(LHS);
1156 Ops.push_back(RHS);
1157 return getSMaxExpr(Ops);
1158}
1159
1160SCEVHandle ScalarEvolution::getSMaxExpr(std::vector<SCEVHandle> Ops) {
1161 assert(!Ops.empty() && "Cannot get empty smax!");
1162 if (Ops.size() == 1) return Ops[0];
1163
1164 // Sort by complexity, this groups all similar expression types together.
1165 GroupByComplexity(Ops);
1166
1167 // If there are any constants, fold them together.
1168 unsigned Idx = 0;
1169 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
1170 ++Idx;
1171 assert(Idx < Ops.size());
1172 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
1173 // We found two constants, fold them together!
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001174 ConstantInt *Fold = ConstantInt::get(
Nick Lewycky711640a2007-11-25 22:41:31 +00001175 APIntOps::smax(LHSC->getValue()->getValue(),
1176 RHSC->getValue()->getValue()));
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001177 Ops[0] = getConstant(Fold);
1178 Ops.erase(Ops.begin()+1); // Erase the folded element
1179 if (Ops.size() == 1) return Ops[0];
1180 LHSC = cast<SCEVConstant>(Ops[0]);
Nick Lewycky711640a2007-11-25 22:41:31 +00001181 }
1182
1183 // If we are left with a constant -inf, strip it off.
1184 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(true)) {
1185 Ops.erase(Ops.begin());
1186 --Idx;
1187 }
1188 }
1189
1190 if (Ops.size() == 1) return Ops[0];
1191
1192 // Find the first SMax
1193 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scSMaxExpr)
1194 ++Idx;
1195
1196 // Check to see if one of the operands is an SMax. If so, expand its operands
1197 // onto our operand list, and recurse to simplify.
1198 if (Idx < Ops.size()) {
1199 bool DeletedSMax = false;
1200 while (SCEVSMaxExpr *SMax = dyn_cast<SCEVSMaxExpr>(Ops[Idx])) {
1201 Ops.insert(Ops.end(), SMax->op_begin(), SMax->op_end());
1202 Ops.erase(Ops.begin()+Idx);
1203 DeletedSMax = true;
1204 }
1205
1206 if (DeletedSMax)
1207 return getSMaxExpr(Ops);
1208 }
1209
1210 // Okay, check to see if the same value occurs in the operand list twice. If
1211 // so, delete one. Since we sorted the list, these values are required to
1212 // be adjacent.
1213 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1214 if (Ops[i] == Ops[i+1]) { // X smax Y smax Y --> X smax Y
1215 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
1216 --i; --e;
1217 }
1218
1219 if (Ops.size() == 1) return Ops[0];
1220
1221 assert(!Ops.empty() && "Reduced smax down to nothing!");
1222
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001223 // Okay, it looks like we really DO need an smax expr. Check to see if we
Nick Lewycky711640a2007-11-25 22:41:31 +00001224 // already have one, otherwise create a new one.
1225 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
1226 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scSMaxExpr,
1227 SCEVOps)];
1228 if (Result == 0) Result = new SCEVSMaxExpr(Ops);
1229 return Result;
1230}
1231
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001232SCEVHandle ScalarEvolution::getUMaxExpr(const SCEVHandle &LHS,
1233 const SCEVHandle &RHS) {
1234 std::vector<SCEVHandle> Ops;
1235 Ops.push_back(LHS);
1236 Ops.push_back(RHS);
1237 return getUMaxExpr(Ops);
1238}
1239
1240SCEVHandle ScalarEvolution::getUMaxExpr(std::vector<SCEVHandle> Ops) {
1241 assert(!Ops.empty() && "Cannot get empty umax!");
1242 if (Ops.size() == 1) return Ops[0];
1243
1244 // Sort by complexity, this groups all similar expression types together.
1245 GroupByComplexity(Ops);
1246
1247 // If there are any constants, fold them together.
1248 unsigned Idx = 0;
1249 if (SCEVConstant *LHSC = dyn_cast<SCEVConstant>(Ops[0])) {
1250 ++Idx;
1251 assert(Idx < Ops.size());
1252 while (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(Ops[Idx])) {
1253 // We found two constants, fold them together!
1254 ConstantInt *Fold = ConstantInt::get(
1255 APIntOps::umax(LHSC->getValue()->getValue(),
1256 RHSC->getValue()->getValue()));
1257 Ops[0] = getConstant(Fold);
1258 Ops.erase(Ops.begin()+1); // Erase the folded element
1259 if (Ops.size() == 1) return Ops[0];
1260 LHSC = cast<SCEVConstant>(Ops[0]);
1261 }
1262
1263 // If we are left with a constant zero, strip it off.
1264 if (cast<SCEVConstant>(Ops[0])->getValue()->isMinValue(false)) {
1265 Ops.erase(Ops.begin());
1266 --Idx;
1267 }
1268 }
1269
1270 if (Ops.size() == 1) return Ops[0];
1271
1272 // Find the first UMax
1273 while (Idx < Ops.size() && Ops[Idx]->getSCEVType() < scUMaxExpr)
1274 ++Idx;
1275
1276 // Check to see if one of the operands is a UMax. If so, expand its operands
1277 // onto our operand list, and recurse to simplify.
1278 if (Idx < Ops.size()) {
1279 bool DeletedUMax = false;
1280 while (SCEVUMaxExpr *UMax = dyn_cast<SCEVUMaxExpr>(Ops[Idx])) {
1281 Ops.insert(Ops.end(), UMax->op_begin(), UMax->op_end());
1282 Ops.erase(Ops.begin()+Idx);
1283 DeletedUMax = true;
1284 }
1285
1286 if (DeletedUMax)
1287 return getUMaxExpr(Ops);
1288 }
1289
1290 // Okay, check to see if the same value occurs in the operand list twice. If
1291 // so, delete one. Since we sorted the list, these values are required to
1292 // be adjacent.
1293 for (unsigned i = 0, e = Ops.size()-1; i != e; ++i)
1294 if (Ops[i] == Ops[i+1]) { // X umax Y umax Y --> X umax Y
1295 Ops.erase(Ops.begin()+i, Ops.begin()+i+1);
1296 --i; --e;
1297 }
1298
1299 if (Ops.size() == 1) return Ops[0];
1300
1301 assert(!Ops.empty() && "Reduced umax down to nothing!");
1302
1303 // Okay, it looks like we really DO need a umax expr. Check to see if we
1304 // already have one, otherwise create a new one.
1305 std::vector<SCEV*> SCEVOps(Ops.begin(), Ops.end());
1306 SCEVCommutativeExpr *&Result = (*SCEVCommExprs)[std::make_pair(scUMaxExpr,
1307 SCEVOps)];
1308 if (Result == 0) Result = new SCEVUMaxExpr(Ops);
1309 return Result;
1310}
1311
Dan Gohman89f85052007-10-22 18:31:58 +00001312SCEVHandle ScalarEvolution::getUnknown(Value *V) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001313 if (ConstantInt *CI = dyn_cast<ConstantInt>(V))
Dan Gohman89f85052007-10-22 18:31:58 +00001314 return getConstant(CI);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001315 SCEVUnknown *&Result = (*SCEVUnknowns)[V];
1316 if (Result == 0) Result = new SCEVUnknown(V);
1317 return Result;
1318}
1319
1320
1321//===----------------------------------------------------------------------===//
1322// ScalarEvolutionsImpl Definition and Implementation
1323//===----------------------------------------------------------------------===//
1324//
1325/// ScalarEvolutionsImpl - This class implements the main driver for the scalar
1326/// evolution code.
1327///
1328namespace {
1329 struct VISIBILITY_HIDDEN ScalarEvolutionsImpl {
Dan Gohman89f85052007-10-22 18:31:58 +00001330 /// SE - A reference to the public ScalarEvolution object.
1331 ScalarEvolution &SE;
1332
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001333 /// F - The function we are analyzing.
1334 ///
1335 Function &F;
1336
1337 /// LI - The loop information for the function we are currently analyzing.
1338 ///
1339 LoopInfo &LI;
1340
1341 /// UnknownValue - This SCEV is used to represent unknown trip counts and
1342 /// things.
1343 SCEVHandle UnknownValue;
1344
1345 /// Scalars - This is a cache of the scalars we have analyzed so far.
1346 ///
1347 std::map<Value*, SCEVHandle> Scalars;
1348
1349 /// IterationCounts - Cache the iteration count of the loops for this
1350 /// function as they are computed.
1351 std::map<const Loop*, SCEVHandle> IterationCounts;
1352
1353 /// ConstantEvolutionLoopExitValue - This map contains entries for all of
1354 /// the PHI instructions that we attempt to compute constant evolutions for.
1355 /// This allows us to avoid potentially expensive recomputation of these
1356 /// properties. An instruction maps to null if we are unable to compute its
1357 /// exit value.
1358 std::map<PHINode*, Constant*> ConstantEvolutionLoopExitValue;
1359
1360 public:
Dan Gohman89f85052007-10-22 18:31:58 +00001361 ScalarEvolutionsImpl(ScalarEvolution &se, Function &f, LoopInfo &li)
1362 : SE(se), F(f), LI(li), UnknownValue(new SCEVCouldNotCompute()) {}
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001363
1364 /// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
1365 /// expression and create a new one.
1366 SCEVHandle getSCEV(Value *V);
1367
1368 /// hasSCEV - Return true if the SCEV for this value has already been
1369 /// computed.
1370 bool hasSCEV(Value *V) const {
1371 return Scalars.count(V);
1372 }
1373
1374 /// setSCEV - Insert the specified SCEV into the map of current SCEVs for
1375 /// the specified value.
1376 void setSCEV(Value *V, const SCEVHandle &H) {
1377 bool isNew = Scalars.insert(std::make_pair(V, H)).second;
1378 assert(isNew && "This entry already existed!");
1379 }
1380
1381
1382 /// getSCEVAtScope - Compute the value of the specified expression within
1383 /// the indicated loop (which may be null to indicate in no loop). If the
1384 /// expression cannot be evaluated, return UnknownValue itself.
1385 SCEVHandle getSCEVAtScope(SCEV *V, const Loop *L);
1386
1387
1388 /// hasLoopInvariantIterationCount - Return true if the specified loop has
1389 /// an analyzable loop-invariant iteration count.
1390 bool hasLoopInvariantIterationCount(const Loop *L);
1391
1392 /// getIterationCount - If the specified loop has a predictable iteration
1393 /// count, return it. Note that it is not valid to call this method on a
1394 /// loop without a loop-invariant iteration count.
1395 SCEVHandle getIterationCount(const Loop *L);
1396
1397 /// deleteValueFromRecords - This method should be called by the
1398 /// client before it removes a value from the program, to make sure
1399 /// that no dangling references are left around.
1400 void deleteValueFromRecords(Value *V);
1401
1402 private:
1403 /// createSCEV - We know that there is no SCEV for the specified value.
1404 /// Analyze the expression.
1405 SCEVHandle createSCEV(Value *V);
1406
1407 /// createNodeForPHI - Provide the special handling we need to analyze PHI
1408 /// SCEVs.
1409 SCEVHandle createNodeForPHI(PHINode *PN);
1410
1411 /// ReplaceSymbolicValueWithConcrete - This looks up the computed SCEV value
1412 /// for the specified instruction and replaces any references to the
1413 /// symbolic value SymName with the specified value. This is used during
1414 /// PHI resolution.
1415 void ReplaceSymbolicValueWithConcrete(Instruction *I,
1416 const SCEVHandle &SymName,
1417 const SCEVHandle &NewVal);
1418
1419 /// ComputeIterationCount - Compute the number of times the specified loop
1420 /// will iterate.
1421 SCEVHandle ComputeIterationCount(const Loop *L);
1422
1423 /// ComputeLoadConstantCompareIterationCount - Given an exit condition of
Nick Lewycky3a8a41f2007-11-20 08:44:50 +00001424 /// 'icmp op load X, cst', try to see if we can compute the trip count.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001425 SCEVHandle ComputeLoadConstantCompareIterationCount(LoadInst *LI,
1426 Constant *RHS,
1427 const Loop *L,
1428 ICmpInst::Predicate p);
1429
1430 /// ComputeIterationCountExhaustively - If the trip is known to execute a
1431 /// constant number of times (the condition evolves only from constants),
1432 /// try to evaluate a few iterations of the loop until we get the exit
1433 /// condition gets a value of ExitWhen (true or false). If we cannot
1434 /// evaluate the trip count of the loop, return UnknownValue.
1435 SCEVHandle ComputeIterationCountExhaustively(const Loop *L, Value *Cond,
1436 bool ExitWhen);
1437
1438 /// HowFarToZero - Return the number of times a backedge comparing the
1439 /// specified value to zero will execute. If not computable, return
1440 /// UnknownValue.
1441 SCEVHandle HowFarToZero(SCEV *V, const Loop *L);
1442
1443 /// HowFarToNonZero - Return the number of times a backedge checking the
1444 /// specified value for nonzero will execute. If not computable, return
1445 /// UnknownValue.
1446 SCEVHandle HowFarToNonZero(SCEV *V, const Loop *L);
1447
1448 /// HowManyLessThans - Return the number of times a backedge containing the
1449 /// specified less-than comparison will execute. If not computable, return
Nick Lewyckyb7c28942007-08-06 19:21:00 +00001450 /// UnknownValue. isSigned specifies whether the less-than is signed.
1451 SCEVHandle HowManyLessThans(SCEV *LHS, SCEV *RHS, const Loop *L,
1452 bool isSigned);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001453
1454 /// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
1455 /// in the header of its containing loop, we know the loop executes a
1456 /// constant number of times, and the PHI node is just a recurrence
1457 /// involving constants, fold it.
1458 Constant *getConstantEvolutionLoopExitValue(PHINode *PN, const APInt& Its,
1459 const Loop *L);
1460 };
1461}
1462
1463//===----------------------------------------------------------------------===//
1464// Basic SCEV Analysis and PHI Idiom Recognition Code
1465//
1466
1467/// deleteValueFromRecords - This method should be called by the
1468/// client before it removes an instruction from the program, to make sure
1469/// that no dangling references are left around.
1470void ScalarEvolutionsImpl::deleteValueFromRecords(Value *V) {
1471 SmallVector<Value *, 16> Worklist;
1472
1473 if (Scalars.erase(V)) {
1474 if (PHINode *PN = dyn_cast<PHINode>(V))
1475 ConstantEvolutionLoopExitValue.erase(PN);
1476 Worklist.push_back(V);
1477 }
1478
1479 while (!Worklist.empty()) {
1480 Value *VV = Worklist.back();
1481 Worklist.pop_back();
1482
1483 for (Instruction::use_iterator UI = VV->use_begin(), UE = VV->use_end();
1484 UI != UE; ++UI) {
1485 Instruction *Inst = cast<Instruction>(*UI);
1486 if (Scalars.erase(Inst)) {
1487 if (PHINode *PN = dyn_cast<PHINode>(VV))
1488 ConstantEvolutionLoopExitValue.erase(PN);
1489 Worklist.push_back(Inst);
1490 }
1491 }
1492 }
1493}
1494
1495
1496/// getSCEV - Return an existing SCEV if it exists, otherwise analyze the
1497/// expression and create a new one.
1498SCEVHandle ScalarEvolutionsImpl::getSCEV(Value *V) {
1499 assert(V->getType() != Type::VoidTy && "Can't analyze void expressions!");
1500
1501 std::map<Value*, SCEVHandle>::iterator I = Scalars.find(V);
1502 if (I != Scalars.end()) return I->second;
1503 SCEVHandle S = createSCEV(V);
1504 Scalars.insert(std::make_pair(V, S));
1505 return S;
1506}
1507
1508/// ReplaceSymbolicValueWithConcrete - This looks up the computed SCEV value for
1509/// the specified instruction and replaces any references to the symbolic value
1510/// SymName with the specified value. This is used during PHI resolution.
1511void ScalarEvolutionsImpl::
1512ReplaceSymbolicValueWithConcrete(Instruction *I, const SCEVHandle &SymName,
1513 const SCEVHandle &NewVal) {
1514 std::map<Value*, SCEVHandle>::iterator SI = Scalars.find(I);
1515 if (SI == Scalars.end()) return;
1516
1517 SCEVHandle NV =
Dan Gohman89f85052007-10-22 18:31:58 +00001518 SI->second->replaceSymbolicValuesWithConcrete(SymName, NewVal, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001519 if (NV == SI->second) return; // No change.
1520
1521 SI->second = NV; // Update the scalars map!
1522
1523 // Any instruction values that use this instruction might also need to be
1524 // updated!
1525 for (Value::use_iterator UI = I->use_begin(), E = I->use_end();
1526 UI != E; ++UI)
1527 ReplaceSymbolicValueWithConcrete(cast<Instruction>(*UI), SymName, NewVal);
1528}
1529
1530/// createNodeForPHI - PHI nodes have two cases. Either the PHI node exists in
1531/// a loop header, making it a potential recurrence, or it doesn't.
1532///
1533SCEVHandle ScalarEvolutionsImpl::createNodeForPHI(PHINode *PN) {
1534 if (PN->getNumIncomingValues() == 2) // The loops have been canonicalized.
1535 if (const Loop *L = LI.getLoopFor(PN->getParent()))
1536 if (L->getHeader() == PN->getParent()) {
1537 // If it lives in the loop header, it has two incoming values, one
1538 // from outside the loop, and one from inside.
1539 unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0));
1540 unsigned BackEdge = IncomingEdge^1;
1541
1542 // While we are analyzing this PHI node, handle its value symbolically.
Dan Gohman89f85052007-10-22 18:31:58 +00001543 SCEVHandle SymbolicName = SE.getUnknown(PN);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001544 assert(Scalars.find(PN) == Scalars.end() &&
1545 "PHI node already processed?");
1546 Scalars.insert(std::make_pair(PN, SymbolicName));
1547
1548 // Using this symbolic name for the PHI, analyze the value coming around
1549 // the back-edge.
1550 SCEVHandle BEValue = getSCEV(PN->getIncomingValue(BackEdge));
1551
1552 // NOTE: If BEValue is loop invariant, we know that the PHI node just
1553 // has a special value for the first iteration of the loop.
1554
1555 // If the value coming around the backedge is an add with the symbolic
1556 // value we just inserted, then we found a simple induction variable!
1557 if (SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(BEValue)) {
1558 // If there is a single occurrence of the symbolic value, replace it
1559 // with a recurrence.
1560 unsigned FoundIndex = Add->getNumOperands();
1561 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
1562 if (Add->getOperand(i) == SymbolicName)
1563 if (FoundIndex == e) {
1564 FoundIndex = i;
1565 break;
1566 }
1567
1568 if (FoundIndex != Add->getNumOperands()) {
1569 // Create an add with everything but the specified operand.
1570 std::vector<SCEVHandle> Ops;
1571 for (unsigned i = 0, e = Add->getNumOperands(); i != e; ++i)
1572 if (i != FoundIndex)
1573 Ops.push_back(Add->getOperand(i));
Dan Gohman89f85052007-10-22 18:31:58 +00001574 SCEVHandle Accum = SE.getAddExpr(Ops);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001575
1576 // This is not a valid addrec if the step amount is varying each
1577 // loop iteration, but is not itself an addrec in this loop.
1578 if (Accum->isLoopInvariant(L) ||
1579 (isa<SCEVAddRecExpr>(Accum) &&
1580 cast<SCEVAddRecExpr>(Accum)->getLoop() == L)) {
1581 SCEVHandle StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
Dan Gohman89f85052007-10-22 18:31:58 +00001582 SCEVHandle PHISCEV = SE.getAddRecExpr(StartVal, Accum, L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001583
1584 // Okay, for the entire analysis of this edge we assumed the PHI
1585 // to be symbolic. We now need to go back and update all of the
1586 // entries for the scalars that use the PHI (except for the PHI
1587 // itself) to use the new analyzed value instead of the "symbolic"
1588 // value.
1589 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
1590 return PHISCEV;
1591 }
1592 }
1593 } else if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(BEValue)) {
1594 // Otherwise, this could be a loop like this:
1595 // i = 0; for (j = 1; ..; ++j) { .... i = j; }
1596 // In this case, j = {1,+,1} and BEValue is j.
1597 // Because the other in-value of i (0) fits the evolution of BEValue
1598 // i really is an addrec evolution.
1599 if (AddRec->getLoop() == L && AddRec->isAffine()) {
1600 SCEVHandle StartVal = getSCEV(PN->getIncomingValue(IncomingEdge));
1601
1602 // If StartVal = j.start - j.stride, we can use StartVal as the
1603 // initial step of the addrec evolution.
Dan Gohman89f85052007-10-22 18:31:58 +00001604 if (StartVal == SE.getMinusSCEV(AddRec->getOperand(0),
1605 AddRec->getOperand(1))) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001606 SCEVHandle PHISCEV =
Dan Gohman89f85052007-10-22 18:31:58 +00001607 SE.getAddRecExpr(StartVal, AddRec->getOperand(1), L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001608
1609 // Okay, for the entire analysis of this edge we assumed the PHI
1610 // to be symbolic. We now need to go back and update all of the
1611 // entries for the scalars that use the PHI (except for the PHI
1612 // itself) to use the new analyzed value instead of the "symbolic"
1613 // value.
1614 ReplaceSymbolicValueWithConcrete(PN, SymbolicName, PHISCEV);
1615 return PHISCEV;
1616 }
1617 }
1618 }
1619
1620 return SymbolicName;
1621 }
1622
1623 // If it's not a loop phi, we can't handle it yet.
Dan Gohman89f85052007-10-22 18:31:58 +00001624 return SE.getUnknown(PN);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001625}
1626
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001627/// GetMinTrailingZeros - Determine the minimum number of zero bits that S is
1628/// guaranteed to end in (at every loop iteration). It is, at the same time,
1629/// the minimum number of times S is divisible by 2. For example, given {4,+,8}
1630/// it returns 2. If S is guaranteed to be 0, it returns the bitwidth of S.
1631static uint32_t GetMinTrailingZeros(SCEVHandle S) {
1632 if (SCEVConstant *C = dyn_cast<SCEVConstant>(S))
Chris Lattner6ecce2a2007-11-23 22:36:49 +00001633 return C->getValue()->getValue().countTrailingZeros();
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001634
Nick Lewycky3a8a41f2007-11-20 08:44:50 +00001635 if (SCEVTruncateExpr *T = dyn_cast<SCEVTruncateExpr>(S))
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001636 return std::min(GetMinTrailingZeros(T->getOperand()), T->getBitWidth());
1637
1638 if (SCEVZeroExtendExpr *E = dyn_cast<SCEVZeroExtendExpr>(S)) {
1639 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
1640 return OpRes == E->getOperand()->getBitWidth() ? E->getBitWidth() : OpRes;
1641 }
1642
1643 if (SCEVSignExtendExpr *E = dyn_cast<SCEVSignExtendExpr>(S)) {
1644 uint32_t OpRes = GetMinTrailingZeros(E->getOperand());
1645 return OpRes == E->getOperand()->getBitWidth() ? E->getBitWidth() : OpRes;
1646 }
1647
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001648 if (SCEVAddExpr *A = dyn_cast<SCEVAddExpr>(S)) {
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001649 // The result is the min of all operands results.
1650 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
1651 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
1652 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
1653 return MinOpRes;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001654 }
1655
1656 if (SCEVMulExpr *M = dyn_cast<SCEVMulExpr>(S)) {
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001657 // The result is the sum of all operands results.
1658 uint32_t SumOpRes = GetMinTrailingZeros(M->getOperand(0));
1659 uint32_t BitWidth = M->getBitWidth();
1660 for (unsigned i = 1, e = M->getNumOperands();
1661 SumOpRes != BitWidth && i != e; ++i)
1662 SumOpRes = std::min(SumOpRes + GetMinTrailingZeros(M->getOperand(i)),
1663 BitWidth);
1664 return SumOpRes;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001665 }
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001666
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001667 if (SCEVAddRecExpr *A = dyn_cast<SCEVAddRecExpr>(S)) {
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001668 // The result is the min of all operands results.
1669 uint32_t MinOpRes = GetMinTrailingZeros(A->getOperand(0));
1670 for (unsigned i = 1, e = A->getNumOperands(); MinOpRes && i != e; ++i)
1671 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(A->getOperand(i)));
1672 return MinOpRes;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001673 }
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001674
Nick Lewycky711640a2007-11-25 22:41:31 +00001675 if (SCEVSMaxExpr *M = dyn_cast<SCEVSMaxExpr>(S)) {
1676 // The result is the min of all operands results.
1677 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
1678 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
1679 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
1680 return MinOpRes;
1681 }
1682
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001683 if (SCEVUMaxExpr *M = dyn_cast<SCEVUMaxExpr>(S)) {
1684 // The result is the min of all operands results.
1685 uint32_t MinOpRes = GetMinTrailingZeros(M->getOperand(0));
1686 for (unsigned i = 1, e = M->getNumOperands(); MinOpRes && i != e; ++i)
1687 MinOpRes = std::min(MinOpRes, GetMinTrailingZeros(M->getOperand(i)));
1688 return MinOpRes;
1689 }
1690
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +00001691 // SCEVUDivExpr, SCEVUnknown
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001692 return 0;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001693}
1694
1695/// createSCEV - We know that there is no SCEV for the specified value.
1696/// Analyze the expression.
1697///
1698SCEVHandle ScalarEvolutionsImpl::createSCEV(Value *V) {
Chris Lattner3fff4642007-11-23 08:46:22 +00001699 if (!isa<IntegerType>(V->getType()))
1700 return SE.getUnknown(V);
1701
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001702 if (Instruction *I = dyn_cast<Instruction>(V)) {
1703 switch (I->getOpcode()) {
1704 case Instruction::Add:
Dan Gohman89f85052007-10-22 18:31:58 +00001705 return SE.getAddExpr(getSCEV(I->getOperand(0)),
1706 getSCEV(I->getOperand(1)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001707 case Instruction::Mul:
Dan Gohman89f85052007-10-22 18:31:58 +00001708 return SE.getMulExpr(getSCEV(I->getOperand(0)),
1709 getSCEV(I->getOperand(1)));
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +00001710 case Instruction::UDiv:
1711 return SE.getUDivExpr(getSCEV(I->getOperand(0)),
Dan Gohman89f85052007-10-22 18:31:58 +00001712 getSCEV(I->getOperand(1)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001713 case Instruction::Sub:
Dan Gohman89f85052007-10-22 18:31:58 +00001714 return SE.getMinusSCEV(getSCEV(I->getOperand(0)),
1715 getSCEV(I->getOperand(1)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001716 case Instruction::Or:
1717 // If the RHS of the Or is a constant, we may have something like:
Nick Lewyckyef947492007-11-20 08:24:44 +00001718 // X*4+1 which got turned into X*4|1. Handle this as an Add so loop
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001719 // optimizations will transparently handle this case.
Nick Lewyckyef947492007-11-20 08:24:44 +00001720 //
1721 // In order for this transformation to be safe, the LHS must be of the
1722 // form X*(2^n) and the Or constant must be less than 2^n.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001723 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
1724 SCEVHandle LHS = getSCEV(I->getOperand(0));
Nick Lewyckyef947492007-11-20 08:24:44 +00001725 const APInt &CIVal = CI->getValue();
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001726 if (GetMinTrailingZeros(LHS) >=
Nick Lewyckyef947492007-11-20 08:24:44 +00001727 (CIVal.getBitWidth() - CIVal.countLeadingZeros()))
Nick Lewycky4cb604b2007-11-22 07:59:40 +00001728 return SE.getAddExpr(LHS, getSCEV(I->getOperand(1)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001729 }
1730 break;
1731 case Instruction::Xor:
1732 // If the RHS of the xor is a signbit, then this is just an add.
1733 // Instcombine turns add of signbit into xor as a strength reduction step.
1734 if (ConstantInt *CI = dyn_cast<ConstantInt>(I->getOperand(1))) {
1735 if (CI->getValue().isSignBit())
Dan Gohman89f85052007-10-22 18:31:58 +00001736 return SE.getAddExpr(getSCEV(I->getOperand(0)),
1737 getSCEV(I->getOperand(1)));
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001738 else if (CI->isAllOnesValue())
1739 return SE.getNotSCEV(getSCEV(I->getOperand(0)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001740 }
1741 break;
1742
1743 case Instruction::Shl:
1744 // Turn shift left of a constant amount into a multiply.
1745 if (ConstantInt *SA = dyn_cast<ConstantInt>(I->getOperand(1))) {
1746 uint32_t BitWidth = cast<IntegerType>(V->getType())->getBitWidth();
1747 Constant *X = ConstantInt::get(
1748 APInt(BitWidth, 1).shl(SA->getLimitedValue(BitWidth)));
Dan Gohman89f85052007-10-22 18:31:58 +00001749 return SE.getMulExpr(getSCEV(I->getOperand(0)), getSCEV(X));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001750 }
1751 break;
1752
1753 case Instruction::Trunc:
Dan Gohman89f85052007-10-22 18:31:58 +00001754 return SE.getTruncateExpr(getSCEV(I->getOperand(0)), I->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001755
1756 case Instruction::ZExt:
Dan Gohman89f85052007-10-22 18:31:58 +00001757 return SE.getZeroExtendExpr(getSCEV(I->getOperand(0)), I->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001758
1759 case Instruction::SExt:
Dan Gohman89f85052007-10-22 18:31:58 +00001760 return SE.getSignExtendExpr(getSCEV(I->getOperand(0)), I->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001761
1762 case Instruction::BitCast:
1763 // BitCasts are no-op casts so we just eliminate the cast.
1764 if (I->getType()->isInteger() &&
1765 I->getOperand(0)->getType()->isInteger())
1766 return getSCEV(I->getOperand(0));
1767 break;
1768
1769 case Instruction::PHI:
1770 return createNodeForPHI(cast<PHINode>(I));
1771
Nick Lewycky711640a2007-11-25 22:41:31 +00001772 case Instruction::Select:
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001773 // This could be a smax or umax that was lowered earlier.
1774 // Try to recover it.
Nick Lewycky711640a2007-11-25 22:41:31 +00001775 if (ICmpInst *ICI = dyn_cast<ICmpInst>(I->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 == I->getOperand(1) && RHS == I->getOperand(2))
1786 return SE.getSMaxExpr(getSCEV(LHS), getSCEV(RHS));
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00001787 else if (LHS == I->getOperand(2) && RHS == I->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 == I->getOperand(1) && RHS == I->getOperand(2))
1800 return SE.getUMaxExpr(getSCEV(LHS), getSCEV(RHS));
1801 else if (LHS == I->getOperand(2) && RHS == I->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;
Nick Lewycky711640a2007-11-25 22:41:31 +00001806 default:
1807 break;
1808 }
1809 }
1810
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001811 default: // We cannot analyze this expression.
1812 break;
1813 }
1814 }
1815
Dan Gohman89f85052007-10-22 18:31:58 +00001816 return SE.getUnknown(V);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001817}
1818
1819
1820
1821//===----------------------------------------------------------------------===//
1822// Iteration Count Computation Code
1823//
1824
1825/// getIterationCount - If the specified loop has a predictable iteration
1826/// count, return it. Note that it is not valid to call this method on a
1827/// loop without a loop-invariant iteration count.
1828SCEVHandle ScalarEvolutionsImpl::getIterationCount(const Loop *L) {
1829 std::map<const Loop*, SCEVHandle>::iterator I = IterationCounts.find(L);
1830 if (I == IterationCounts.end()) {
1831 SCEVHandle ItCount = ComputeIterationCount(L);
1832 I = IterationCounts.insert(std::make_pair(L, ItCount)).first;
1833 if (ItCount != UnknownValue) {
1834 assert(ItCount->isLoopInvariant(L) &&
1835 "Computed trip count isn't loop invariant for loop!");
1836 ++NumTripCountsComputed;
1837 } else if (isa<PHINode>(L->getHeader()->begin())) {
1838 // Only count loops that have phi nodes as not being computable.
1839 ++NumTripCountsNotComputed;
1840 }
1841 }
1842 return I->second;
1843}
1844
1845/// ComputeIterationCount - Compute the number of times the specified loop
1846/// will iterate.
1847SCEVHandle ScalarEvolutionsImpl::ComputeIterationCount(const Loop *L) {
1848 // If the loop has a non-one exit block count, we can't analyze it.
Devang Patel02451fa2007-08-21 00:31:24 +00001849 SmallVector<BasicBlock*, 8> ExitBlocks;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001850 L->getExitBlocks(ExitBlocks);
1851 if (ExitBlocks.size() != 1) return UnknownValue;
1852
1853 // Okay, there is one exit block. Try to find the condition that causes the
1854 // loop to be exited.
1855 BasicBlock *ExitBlock = ExitBlocks[0];
1856
1857 BasicBlock *ExitingBlock = 0;
1858 for (pred_iterator PI = pred_begin(ExitBlock), E = pred_end(ExitBlock);
1859 PI != E; ++PI)
1860 if (L->contains(*PI)) {
1861 if (ExitingBlock == 0)
1862 ExitingBlock = *PI;
1863 else
1864 return UnknownValue; // More than one block exiting!
1865 }
1866 assert(ExitingBlock && "No exits from loop, something is broken!");
1867
1868 // Okay, we've computed the exiting block. See what condition causes us to
1869 // exit.
1870 //
1871 // FIXME: we should be able to handle switch instructions (with a single exit)
1872 BranchInst *ExitBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
1873 if (ExitBr == 0) return UnknownValue;
1874 assert(ExitBr->isConditional() && "If unconditional, it can't be in loop!");
1875
1876 // At this point, we know we have a conditional branch that determines whether
1877 // the loop is exited. However, we don't know if the branch is executed each
1878 // time through the loop. If not, then the execution count of the branch will
1879 // not be equal to the trip count of the loop.
1880 //
1881 // Currently we check for this by checking to see if the Exit branch goes to
1882 // the loop header. If so, we know it will always execute the same number of
1883 // times as the loop. We also handle the case where the exit block *is* the
1884 // loop header. This is common for un-rotated loops. More extensive analysis
1885 // could be done to handle more cases here.
1886 if (ExitBr->getSuccessor(0) != L->getHeader() &&
1887 ExitBr->getSuccessor(1) != L->getHeader() &&
1888 ExitBr->getParent() != L->getHeader())
1889 return UnknownValue;
1890
1891 ICmpInst *ExitCond = dyn_cast<ICmpInst>(ExitBr->getCondition());
1892
Nick Lewyckyb3d24332008-02-21 08:34:02 +00001893 // If it's not an integer comparison then compute it the hard way.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001894 // Note that ICmpInst deals with pointer comparisons too so we must check
1895 // the type of the operand.
1896 if (ExitCond == 0 || isa<PointerType>(ExitCond->getOperand(0)->getType()))
1897 return ComputeIterationCountExhaustively(L, ExitBr->getCondition(),
1898 ExitBr->getSuccessor(0) == ExitBlock);
1899
1900 // If the condition was exit on true, convert the condition to exit on false
1901 ICmpInst::Predicate Cond;
1902 if (ExitBr->getSuccessor(1) == ExitBlock)
1903 Cond = ExitCond->getPredicate();
1904 else
1905 Cond = ExitCond->getInversePredicate();
1906
1907 // Handle common loops like: for (X = "string"; *X; ++X)
1908 if (LoadInst *LI = dyn_cast<LoadInst>(ExitCond->getOperand(0)))
1909 if (Constant *RHS = dyn_cast<Constant>(ExitCond->getOperand(1))) {
1910 SCEVHandle ItCnt =
1911 ComputeLoadConstantCompareIterationCount(LI, RHS, L, Cond);
1912 if (!isa<SCEVCouldNotCompute>(ItCnt)) return ItCnt;
1913 }
1914
1915 SCEVHandle LHS = getSCEV(ExitCond->getOperand(0));
1916 SCEVHandle RHS = getSCEV(ExitCond->getOperand(1));
1917
1918 // Try to evaluate any dependencies out of the loop.
1919 SCEVHandle Tmp = getSCEVAtScope(LHS, L);
1920 if (!isa<SCEVCouldNotCompute>(Tmp)) LHS = Tmp;
1921 Tmp = getSCEVAtScope(RHS, L);
1922 if (!isa<SCEVCouldNotCompute>(Tmp)) RHS = Tmp;
1923
1924 // At this point, we would like to compute how many iterations of the
1925 // loop the predicate will return true for these inputs.
Evan Cheng1d183082008-02-25 03:57:32 +00001926 if (isa<SCEVConstant>(LHS) && !isa<SCEVConstant>(RHS)) {
1927 // If there is a constant, force it into the RHS.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001928 std::swap(LHS, RHS);
1929 Cond = ICmpInst::getSwappedPredicate(Cond);
1930 }
1931
1932 // FIXME: think about handling pointer comparisons! i.e.:
1933 // while (P != P+100) ++P;
1934
1935 // If we have a comparison of a chrec against a constant, try to use value
1936 // ranges to answer this query.
1937 if (SCEVConstant *RHSC = dyn_cast<SCEVConstant>(RHS))
1938 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS))
1939 if (AddRec->getLoop() == L) {
1940 // Form the comparison range using the constant of the correct type so
1941 // that the ConstantRange class knows to do a signed or unsigned
1942 // comparison.
1943 ConstantInt *CompVal = RHSC->getValue();
1944 const Type *RealTy = ExitCond->getOperand(0)->getType();
1945 CompVal = dyn_cast<ConstantInt>(
1946 ConstantExpr::getBitCast(CompVal, RealTy));
1947 if (CompVal) {
1948 // Form the constant range.
1949 ConstantRange CompRange(
1950 ICmpInst::makeConstantRange(Cond, CompVal->getValue()));
1951
Dan Gohman89f85052007-10-22 18:31:58 +00001952 SCEVHandle Ret = AddRec->getNumIterationsInRange(CompRange, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001953 if (!isa<SCEVCouldNotCompute>(Ret)) return Ret;
1954 }
1955 }
1956
1957 switch (Cond) {
1958 case ICmpInst::ICMP_NE: { // while (X != Y)
1959 // Convert to: while (X-Y != 0)
Dan Gohman89f85052007-10-22 18:31:58 +00001960 SCEVHandle TC = HowFarToZero(SE.getMinusSCEV(LHS, RHS), L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001961 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
1962 break;
1963 }
1964 case ICmpInst::ICMP_EQ: {
1965 // Convert to: while (X-Y == 0) // while (X == Y)
Dan Gohman89f85052007-10-22 18:31:58 +00001966 SCEVHandle TC = HowFarToNonZero(SE.getMinusSCEV(LHS, RHS), L);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001967 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
1968 break;
1969 }
1970 case ICmpInst::ICMP_SLT: {
Nick Lewyckyb7c28942007-08-06 19:21:00 +00001971 SCEVHandle TC = HowManyLessThans(LHS, RHS, L, true);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001972 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
1973 break;
1974 }
1975 case ICmpInst::ICMP_SGT: {
Dan Gohman89f85052007-10-22 18:31:58 +00001976 SCEVHandle TC = HowManyLessThans(SE.getNegativeSCEV(LHS),
1977 SE.getNegativeSCEV(RHS), L, true);
Nick Lewyckyb7c28942007-08-06 19:21:00 +00001978 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
1979 break;
1980 }
1981 case ICmpInst::ICMP_ULT: {
1982 SCEVHandle TC = HowManyLessThans(LHS, RHS, L, false);
1983 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
1984 break;
1985 }
1986 case ICmpInst::ICMP_UGT: {
Dale Johannesend721b952008-04-20 16:58:57 +00001987 SCEVHandle TC = HowManyLessThans(SE.getNotSCEV(LHS),
Nick Lewycky347e4222008-05-06 04:03:18 +00001988 SE.getNotSCEV(RHS), L, false);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00001989 if (!isa<SCEVCouldNotCompute>(TC)) return TC;
1990 break;
1991 }
1992 default:
1993#if 0
1994 cerr << "ComputeIterationCount ";
1995 if (ExitCond->getOperand(0)->getType()->isUnsigned())
1996 cerr << "[unsigned] ";
1997 cerr << *LHS << " "
1998 << Instruction::getOpcodeName(Instruction::ICmp)
1999 << " " << *RHS << "\n";
2000#endif
2001 break;
2002 }
2003 return ComputeIterationCountExhaustively(L, ExitCond,
2004 ExitBr->getSuccessor(0) == ExitBlock);
2005}
2006
2007static ConstantInt *
Dan Gohman89f85052007-10-22 18:31:58 +00002008EvaluateConstantChrecAtConstant(const SCEVAddRecExpr *AddRec, ConstantInt *C,
2009 ScalarEvolution &SE) {
2010 SCEVHandle InVal = SE.getConstant(C);
2011 SCEVHandle Val = AddRec->evaluateAtIteration(InVal, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002012 assert(isa<SCEVConstant>(Val) &&
2013 "Evaluation of SCEV at constant didn't fold correctly?");
2014 return cast<SCEVConstant>(Val)->getValue();
2015}
2016
2017/// GetAddressedElementFromGlobal - Given a global variable with an initializer
2018/// and a GEP expression (missing the pointer index) indexing into it, return
2019/// the addressed element of the initializer or null if the index expression is
2020/// invalid.
2021static Constant *
2022GetAddressedElementFromGlobal(GlobalVariable *GV,
2023 const std::vector<ConstantInt*> &Indices) {
2024 Constant *Init = GV->getInitializer();
2025 for (unsigned i = 0, e = Indices.size(); i != e; ++i) {
2026 uint64_t Idx = Indices[i]->getZExtValue();
2027 if (ConstantStruct *CS = dyn_cast<ConstantStruct>(Init)) {
2028 assert(Idx < CS->getNumOperands() && "Bad struct index!");
2029 Init = cast<Constant>(CS->getOperand(Idx));
2030 } else if (ConstantArray *CA = dyn_cast<ConstantArray>(Init)) {
2031 if (Idx >= CA->getNumOperands()) return 0; // Bogus program
2032 Init = cast<Constant>(CA->getOperand(Idx));
2033 } else if (isa<ConstantAggregateZero>(Init)) {
2034 if (const StructType *STy = dyn_cast<StructType>(Init->getType())) {
2035 assert(Idx < STy->getNumElements() && "Bad struct index!");
2036 Init = Constant::getNullValue(STy->getElementType(Idx));
2037 } else if (const ArrayType *ATy = dyn_cast<ArrayType>(Init->getType())) {
2038 if (Idx >= ATy->getNumElements()) return 0; // Bogus program
2039 Init = Constant::getNullValue(ATy->getElementType());
2040 } else {
2041 assert(0 && "Unknown constant aggregate type!");
2042 }
2043 return 0;
2044 } else {
2045 return 0; // Unknown initializer type
2046 }
2047 }
2048 return Init;
2049}
2050
2051/// ComputeLoadConstantCompareIterationCount - Given an exit condition of
Nick Lewycky347e4222008-05-06 04:03:18 +00002052/// 'icmp op load X, cst', try to see if we can compute the trip count.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002053SCEVHandle ScalarEvolutionsImpl::
2054ComputeLoadConstantCompareIterationCount(LoadInst *LI, Constant *RHS,
2055 const Loop *L,
2056 ICmpInst::Predicate predicate) {
2057 if (LI->isVolatile()) return UnknownValue;
2058
2059 // Check to see if the loaded pointer is a getelementptr of a global.
2060 GetElementPtrInst *GEP = dyn_cast<GetElementPtrInst>(LI->getOperand(0));
2061 if (!GEP) return UnknownValue;
2062
2063 // Make sure that it is really a constant global we are gepping, with an
2064 // initializer, and make sure the first IDX is really 0.
2065 GlobalVariable *GV = dyn_cast<GlobalVariable>(GEP->getOperand(0));
2066 if (!GV || !GV->isConstant() || !GV->hasInitializer() ||
2067 GEP->getNumOperands() < 3 || !isa<Constant>(GEP->getOperand(1)) ||
2068 !cast<Constant>(GEP->getOperand(1))->isNullValue())
2069 return UnknownValue;
2070
2071 // Okay, we allow one non-constant index into the GEP instruction.
2072 Value *VarIdx = 0;
2073 std::vector<ConstantInt*> Indexes;
2074 unsigned VarIdxNum = 0;
2075 for (unsigned i = 2, e = GEP->getNumOperands(); i != e; ++i)
2076 if (ConstantInt *CI = dyn_cast<ConstantInt>(GEP->getOperand(i))) {
2077 Indexes.push_back(CI);
2078 } else if (!isa<ConstantInt>(GEP->getOperand(i))) {
2079 if (VarIdx) return UnknownValue; // Multiple non-constant idx's.
2080 VarIdx = GEP->getOperand(i);
2081 VarIdxNum = i-2;
2082 Indexes.push_back(0);
2083 }
2084
2085 // Okay, we know we have a (load (gep GV, 0, X)) comparison with a constant.
2086 // Check to see if X is a loop variant variable value now.
2087 SCEVHandle Idx = getSCEV(VarIdx);
2088 SCEVHandle Tmp = getSCEVAtScope(Idx, L);
2089 if (!isa<SCEVCouldNotCompute>(Tmp)) Idx = Tmp;
2090
2091 // We can only recognize very limited forms of loop index expressions, in
2092 // particular, only affine AddRec's like {C1,+,C2}.
2093 SCEVAddRecExpr *IdxExpr = dyn_cast<SCEVAddRecExpr>(Idx);
2094 if (!IdxExpr || !IdxExpr->isAffine() || IdxExpr->isLoopInvariant(L) ||
2095 !isa<SCEVConstant>(IdxExpr->getOperand(0)) ||
2096 !isa<SCEVConstant>(IdxExpr->getOperand(1)))
2097 return UnknownValue;
2098
2099 unsigned MaxSteps = MaxBruteForceIterations;
2100 for (unsigned IterationNum = 0; IterationNum != MaxSteps; ++IterationNum) {
2101 ConstantInt *ItCst =
2102 ConstantInt::get(IdxExpr->getType(), IterationNum);
Dan Gohman89f85052007-10-22 18:31:58 +00002103 ConstantInt *Val = EvaluateConstantChrecAtConstant(IdxExpr, ItCst, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002104
2105 // Form the GEP offset.
2106 Indexes[VarIdxNum] = Val;
2107
2108 Constant *Result = GetAddressedElementFromGlobal(GV, Indexes);
2109 if (Result == 0) break; // Cannot compute!
2110
2111 // Evaluate the condition for this iteration.
2112 Result = ConstantExpr::getICmp(predicate, Result, RHS);
2113 if (!isa<ConstantInt>(Result)) break; // Couldn't decide for sure
2114 if (cast<ConstantInt>(Result)->getValue().isMinValue()) {
2115#if 0
2116 cerr << "\n***\n*** Computed loop count " << *ItCst
2117 << "\n*** From global " << *GV << "*** BB: " << *L->getHeader()
2118 << "***\n";
2119#endif
2120 ++NumArrayLenItCounts;
Dan Gohman89f85052007-10-22 18:31:58 +00002121 return SE.getConstant(ItCst); // Found terminating iteration!
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002122 }
2123 }
2124 return UnknownValue;
2125}
2126
2127
2128/// CanConstantFold - Return true if we can constant fold an instruction of the
2129/// specified type, assuming that all operands were constants.
2130static bool CanConstantFold(const Instruction *I) {
2131 if (isa<BinaryOperator>(I) || isa<CmpInst>(I) ||
2132 isa<SelectInst>(I) || isa<CastInst>(I) || isa<GetElementPtrInst>(I))
2133 return true;
2134
2135 if (const CallInst *CI = dyn_cast<CallInst>(I))
2136 if (const Function *F = CI->getCalledFunction())
Dan Gohmane6e001f2008-01-31 01:05:10 +00002137 return canConstantFoldCallTo(F);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002138 return false;
2139}
2140
2141/// getConstantEvolvingPHI - Given an LLVM value and a loop, return a PHI node
2142/// in the loop that V is derived from. We allow arbitrary operations along the
2143/// way, but the operands of an operation must either be constants or a value
2144/// derived from a constant PHI. If this expression does not fit with these
2145/// constraints, return null.
2146static PHINode *getConstantEvolvingPHI(Value *V, const Loop *L) {
2147 // If this is not an instruction, or if this is an instruction outside of the
2148 // loop, it can't be derived from a loop PHI.
2149 Instruction *I = dyn_cast<Instruction>(V);
2150 if (I == 0 || !L->contains(I->getParent())) return 0;
2151
Anton Korobeynikov357a27d2008-02-20 11:08:44 +00002152 if (PHINode *PN = dyn_cast<PHINode>(I)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002153 if (L->getHeader() == I->getParent())
2154 return PN;
2155 else
2156 // We don't currently keep track of the control flow needed to evaluate
2157 // PHIs, so we cannot handle PHIs inside of loops.
2158 return 0;
Anton Korobeynikov357a27d2008-02-20 11:08:44 +00002159 }
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002160
2161 // If we won't be able to constant fold this expression even if the operands
2162 // are constants, return early.
2163 if (!CanConstantFold(I)) return 0;
2164
2165 // Otherwise, we can evaluate this instruction if all of its operands are
2166 // constant or derived from a PHI node themselves.
2167 PHINode *PHI = 0;
2168 for (unsigned Op = 0, e = I->getNumOperands(); Op != e; ++Op)
2169 if (!(isa<Constant>(I->getOperand(Op)) ||
2170 isa<GlobalValue>(I->getOperand(Op)))) {
2171 PHINode *P = getConstantEvolvingPHI(I->getOperand(Op), L);
2172 if (P == 0) return 0; // Not evolving from PHI
2173 if (PHI == 0)
2174 PHI = P;
2175 else if (PHI != P)
2176 return 0; // Evolving from multiple different PHIs.
2177 }
2178
2179 // This is a expression evolving from a constant PHI!
2180 return PHI;
2181}
2182
2183/// EvaluateExpression - Given an expression that passes the
2184/// getConstantEvolvingPHI predicate, evaluate its value assuming the PHI node
2185/// in the loop has the value PHIVal. If we can't fold this expression for some
2186/// reason, return null.
2187static Constant *EvaluateExpression(Value *V, Constant *PHIVal) {
2188 if (isa<PHINode>(V)) return PHIVal;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002189 if (Constant *C = dyn_cast<Constant>(V)) return C;
2190 Instruction *I = cast<Instruction>(V);
2191
2192 std::vector<Constant*> Operands;
2193 Operands.resize(I->getNumOperands());
2194
2195 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
2196 Operands[i] = EvaluateExpression(I->getOperand(i), PHIVal);
2197 if (Operands[i] == 0) return 0;
2198 }
2199
Chris Lattnerd6e56912007-12-10 22:53:04 +00002200 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
2201 return ConstantFoldCompareInstOperands(CI->getPredicate(),
2202 &Operands[0], Operands.size());
2203 else
2204 return ConstantFoldInstOperands(I->getOpcode(), I->getType(),
2205 &Operands[0], Operands.size());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002206}
2207
2208/// getConstantEvolutionLoopExitValue - If we know that the specified Phi is
2209/// in the header of its containing loop, we know the loop executes a
2210/// constant number of times, and the PHI node is just a recurrence
2211/// involving constants, fold it.
2212Constant *ScalarEvolutionsImpl::
2213getConstantEvolutionLoopExitValue(PHINode *PN, const APInt& Its, const Loop *L){
2214 std::map<PHINode*, Constant*>::iterator I =
2215 ConstantEvolutionLoopExitValue.find(PN);
2216 if (I != ConstantEvolutionLoopExitValue.end())
2217 return I->second;
2218
2219 if (Its.ugt(APInt(Its.getBitWidth(),MaxBruteForceIterations)))
2220 return ConstantEvolutionLoopExitValue[PN] = 0; // Not going to evaluate it.
2221
2222 Constant *&RetVal = ConstantEvolutionLoopExitValue[PN];
2223
2224 // Since the loop is canonicalized, the PHI node must have two entries. One
2225 // entry must be a constant (coming in from outside of the loop), and the
2226 // second must be derived from the same PHI.
2227 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
2228 Constant *StartCST =
2229 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
2230 if (StartCST == 0)
2231 return RetVal = 0; // Must be a constant.
2232
2233 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
2234 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
2235 if (PN2 != PN)
2236 return RetVal = 0; // Not derived from same PHI.
2237
2238 // Execute the loop symbolically to determine the exit value.
2239 if (Its.getActiveBits() >= 32)
2240 return RetVal = 0; // More than 2^32-1 iterations?? Not doing it!
2241
2242 unsigned NumIterations = Its.getZExtValue(); // must be in range
2243 unsigned IterationNum = 0;
2244 for (Constant *PHIVal = StartCST; ; ++IterationNum) {
2245 if (IterationNum == NumIterations)
2246 return RetVal = PHIVal; // Got exit value!
2247
2248 // Compute the value of the PHI node for the next iteration.
2249 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
2250 if (NextPHI == PHIVal)
2251 return RetVal = NextPHI; // Stopped evolving!
2252 if (NextPHI == 0)
2253 return 0; // Couldn't evaluate!
2254 PHIVal = NextPHI;
2255 }
2256}
2257
2258/// ComputeIterationCountExhaustively - If the trip is known to execute a
2259/// constant number of times (the condition evolves only from constants),
2260/// try to evaluate a few iterations of the loop until we get the exit
2261/// condition gets a value of ExitWhen (true or false). If we cannot
2262/// evaluate the trip count of the loop, return UnknownValue.
2263SCEVHandle ScalarEvolutionsImpl::
2264ComputeIterationCountExhaustively(const Loop *L, Value *Cond, bool ExitWhen) {
2265 PHINode *PN = getConstantEvolvingPHI(Cond, L);
2266 if (PN == 0) return UnknownValue;
2267
2268 // Since the loop is canonicalized, the PHI node must have two entries. One
2269 // entry must be a constant (coming in from outside of the loop), and the
2270 // second must be derived from the same PHI.
2271 bool SecondIsBackedge = L->contains(PN->getIncomingBlock(1));
2272 Constant *StartCST =
2273 dyn_cast<Constant>(PN->getIncomingValue(!SecondIsBackedge));
2274 if (StartCST == 0) return UnknownValue; // Must be a constant.
2275
2276 Value *BEValue = PN->getIncomingValue(SecondIsBackedge);
2277 PHINode *PN2 = getConstantEvolvingPHI(BEValue, L);
2278 if (PN2 != PN) return UnknownValue; // Not derived from same PHI.
2279
2280 // Okay, we find a PHI node that defines the trip count of this loop. Execute
2281 // the loop symbolically to determine when the condition gets a value of
2282 // "ExitWhen".
2283 unsigned IterationNum = 0;
2284 unsigned MaxIterations = MaxBruteForceIterations; // Limit analysis.
2285 for (Constant *PHIVal = StartCST;
2286 IterationNum != MaxIterations; ++IterationNum) {
2287 ConstantInt *CondVal =
2288 dyn_cast_or_null<ConstantInt>(EvaluateExpression(Cond, PHIVal));
2289
2290 // Couldn't symbolically evaluate.
2291 if (!CondVal) return UnknownValue;
2292
2293 if (CondVal->getValue() == uint64_t(ExitWhen)) {
2294 ConstantEvolutionLoopExitValue[PN] = PHIVal;
2295 ++NumBruteForceTripCountsComputed;
Dan Gohman89f85052007-10-22 18:31:58 +00002296 return SE.getConstant(ConstantInt::get(Type::Int32Ty, IterationNum));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002297 }
2298
2299 // Compute the value of the PHI node for the next iteration.
2300 Constant *NextPHI = EvaluateExpression(BEValue, PHIVal);
2301 if (NextPHI == 0 || NextPHI == PHIVal)
2302 return UnknownValue; // Couldn't evaluate or not making progress...
2303 PHIVal = NextPHI;
2304 }
2305
2306 // Too many iterations were needed to evaluate.
2307 return UnknownValue;
2308}
2309
2310/// getSCEVAtScope - Compute the value of the specified expression within the
2311/// indicated loop (which may be null to indicate in no loop). If the
2312/// expression cannot be evaluated, return UnknownValue.
2313SCEVHandle ScalarEvolutionsImpl::getSCEVAtScope(SCEV *V, const Loop *L) {
2314 // FIXME: this should be turned into a virtual method on SCEV!
2315
2316 if (isa<SCEVConstant>(V)) return V;
2317
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00002318 // If this instruction is evolved from a constant-evolving PHI, compute the
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002319 // exit value from the loop without using SCEVs.
2320 if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(V)) {
2321 if (Instruction *I = dyn_cast<Instruction>(SU->getValue())) {
2322 const Loop *LI = this->LI[I->getParent()];
2323 if (LI && LI->getParentLoop() == L) // Looking for loop exit value.
2324 if (PHINode *PN = dyn_cast<PHINode>(I))
2325 if (PN->getParent() == LI->getHeader()) {
2326 // Okay, there is no closed form solution for the PHI node. Check
2327 // to see if the loop that contains it has a known iteration count.
2328 // If so, we may be able to force computation of the exit value.
2329 SCEVHandle IterationCount = getIterationCount(LI);
2330 if (SCEVConstant *ICC = dyn_cast<SCEVConstant>(IterationCount)) {
2331 // Okay, we know how many times the containing loop executes. If
2332 // this is a constant evolving PHI node, get the final value at
2333 // the specified iteration number.
2334 Constant *RV = getConstantEvolutionLoopExitValue(PN,
2335 ICC->getValue()->getValue(),
2336 LI);
Dan Gohman89f85052007-10-22 18:31:58 +00002337 if (RV) return SE.getUnknown(RV);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002338 }
2339 }
2340
2341 // Okay, this is an expression that we cannot symbolically evaluate
2342 // into a SCEV. Check to see if it's possible to symbolically evaluate
2343 // the arguments into constants, and if so, try to constant propagate the
2344 // result. This is particularly useful for computing loop exit values.
2345 if (CanConstantFold(I)) {
2346 std::vector<Constant*> Operands;
2347 Operands.reserve(I->getNumOperands());
2348 for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
2349 Value *Op = I->getOperand(i);
2350 if (Constant *C = dyn_cast<Constant>(Op)) {
2351 Operands.push_back(C);
2352 } else {
Chris Lattner3fff4642007-11-23 08:46:22 +00002353 // If any of the operands is non-constant and if they are
2354 // non-integer, don't even try to analyze them with scev techniques.
2355 if (!isa<IntegerType>(Op->getType()))
2356 return V;
2357
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002358 SCEVHandle OpV = getSCEVAtScope(getSCEV(Op), L);
2359 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(OpV))
2360 Operands.push_back(ConstantExpr::getIntegerCast(SC->getValue(),
2361 Op->getType(),
2362 false));
2363 else if (SCEVUnknown *SU = dyn_cast<SCEVUnknown>(OpV)) {
2364 if (Constant *C = dyn_cast<Constant>(SU->getValue()))
2365 Operands.push_back(ConstantExpr::getIntegerCast(C,
2366 Op->getType(),
2367 false));
2368 else
2369 return V;
2370 } else {
2371 return V;
2372 }
2373 }
2374 }
Chris Lattnerd6e56912007-12-10 22:53:04 +00002375
2376 Constant *C;
2377 if (const CmpInst *CI = dyn_cast<CmpInst>(I))
2378 C = ConstantFoldCompareInstOperands(CI->getPredicate(),
2379 &Operands[0], Operands.size());
2380 else
2381 C = ConstantFoldInstOperands(I->getOpcode(), I->getType(),
2382 &Operands[0], Operands.size());
Dan Gohman89f85052007-10-22 18:31:58 +00002383 return SE.getUnknown(C);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002384 }
2385 }
2386
2387 // This is some other type of SCEVUnknown, just return it.
2388 return V;
2389 }
2390
2391 if (SCEVCommutativeExpr *Comm = dyn_cast<SCEVCommutativeExpr>(V)) {
2392 // Avoid performing the look-up in the common case where the specified
2393 // expression has no loop-variant portions.
2394 for (unsigned i = 0, e = Comm->getNumOperands(); i != e; ++i) {
2395 SCEVHandle OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
2396 if (OpAtScope != Comm->getOperand(i)) {
2397 if (OpAtScope == UnknownValue) return UnknownValue;
2398 // Okay, at least one of these operands is loop variant but might be
2399 // foldable. Build a new instance of the folded commutative expression.
2400 std::vector<SCEVHandle> NewOps(Comm->op_begin(), Comm->op_begin()+i);
2401 NewOps.push_back(OpAtScope);
2402
2403 for (++i; i != e; ++i) {
2404 OpAtScope = getSCEVAtScope(Comm->getOperand(i), L);
2405 if (OpAtScope == UnknownValue) return UnknownValue;
2406 NewOps.push_back(OpAtScope);
2407 }
2408 if (isa<SCEVAddExpr>(Comm))
Dan Gohman89f85052007-10-22 18:31:58 +00002409 return SE.getAddExpr(NewOps);
Nick Lewycky711640a2007-11-25 22:41:31 +00002410 if (isa<SCEVMulExpr>(Comm))
2411 return SE.getMulExpr(NewOps);
2412 if (isa<SCEVSMaxExpr>(Comm))
2413 return SE.getSMaxExpr(NewOps);
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00002414 if (isa<SCEVUMaxExpr>(Comm))
2415 return SE.getUMaxExpr(NewOps);
Nick Lewycky711640a2007-11-25 22:41:31 +00002416 assert(0 && "Unknown commutative SCEV type!");
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002417 }
2418 }
2419 // If we got here, all operands are loop invariant.
2420 return Comm;
2421 }
2422
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +00002423 if (SCEVUDivExpr *Div = dyn_cast<SCEVUDivExpr>(V)) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002424 SCEVHandle LHS = getSCEVAtScope(Div->getLHS(), L);
2425 if (LHS == UnknownValue) return LHS;
2426 SCEVHandle RHS = getSCEVAtScope(Div->getRHS(), L);
2427 if (RHS == UnknownValue) return RHS;
2428 if (LHS == Div->getLHS() && RHS == Div->getRHS())
2429 return Div; // must be loop invariant
Wojciech Matyjewicz2211fec2008-02-11 11:03:14 +00002430 return SE.getUDivExpr(LHS, RHS);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002431 }
2432
2433 // If this is a loop recurrence for a loop that does not contain L, then we
2434 // are dealing with the final value computed by the loop.
2435 if (SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V)) {
2436 if (!L || !AddRec->getLoop()->contains(L->getHeader())) {
2437 // To evaluate this recurrence, we need to know how many times the AddRec
2438 // loop iterates. Compute this now.
2439 SCEVHandle IterationCount = getIterationCount(AddRec->getLoop());
2440 if (IterationCount == UnknownValue) return UnknownValue;
Nick Lewyckydbaa60a2008-06-13 04:38:55 +00002441 IterationCount = SE.getTruncateOrZeroExtend(IterationCount,
2442 AddRec->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002443
2444 // If the value is affine, simplify the expression evaluation to just
2445 // Start + Step*IterationCount.
2446 if (AddRec->isAffine())
Dan Gohman89f85052007-10-22 18:31:58 +00002447 return SE.getAddExpr(AddRec->getStart(),
2448 SE.getMulExpr(IterationCount,
2449 AddRec->getOperand(1)));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002450
2451 // Otherwise, evaluate it the hard way.
Dan Gohman89f85052007-10-22 18:31:58 +00002452 return AddRec->evaluateAtIteration(IterationCount, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002453 }
2454 return UnknownValue;
2455 }
2456
2457 //assert(0 && "Unknown SCEV type!");
2458 return UnknownValue;
2459}
2460
2461
2462/// SolveQuadraticEquation - Find the roots of the quadratic equation for the
2463/// given quadratic chrec {L,+,M,+,N}. This returns either the two roots (which
2464/// might be the same) or two SCEVCouldNotCompute objects.
2465///
2466static std::pair<SCEVHandle,SCEVHandle>
Dan Gohman89f85052007-10-22 18:31:58 +00002467SolveQuadraticEquation(const SCEVAddRecExpr *AddRec, ScalarEvolution &SE) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002468 assert(AddRec->getNumOperands() == 3 && "This is not a quadratic chrec!");
2469 SCEVConstant *LC = dyn_cast<SCEVConstant>(AddRec->getOperand(0));
2470 SCEVConstant *MC = dyn_cast<SCEVConstant>(AddRec->getOperand(1));
2471 SCEVConstant *NC = dyn_cast<SCEVConstant>(AddRec->getOperand(2));
2472
2473 // We currently can only solve this if the coefficients are constants.
2474 if (!LC || !MC || !NC) {
2475 SCEV *CNC = new SCEVCouldNotCompute();
2476 return std::make_pair(CNC, CNC);
2477 }
2478
2479 uint32_t BitWidth = LC->getValue()->getValue().getBitWidth();
2480 const APInt &L = LC->getValue()->getValue();
2481 const APInt &M = MC->getValue()->getValue();
2482 const APInt &N = NC->getValue()->getValue();
2483 APInt Two(BitWidth, 2);
2484 APInt Four(BitWidth, 4);
2485
2486 {
2487 using namespace APIntOps;
2488 const APInt& C = L;
2489 // Convert from chrec coefficients to polynomial coefficients AX^2+BX+C
2490 // The B coefficient is M-N/2
2491 APInt B(M);
2492 B -= sdiv(N,Two);
2493
2494 // The A coefficient is N/2
2495 APInt A(N.sdiv(Two));
2496
2497 // Compute the B^2-4ac term.
2498 APInt SqrtTerm(B);
2499 SqrtTerm *= B;
2500 SqrtTerm -= Four * (A * C);
2501
2502 // Compute sqrt(B^2-4ac). This is guaranteed to be the nearest
2503 // integer value or else APInt::sqrt() will assert.
2504 APInt SqrtVal(SqrtTerm.sqrt());
2505
2506 // Compute the two solutions for the quadratic formula.
2507 // The divisions must be performed as signed divisions.
2508 APInt NegB(-B);
2509 APInt TwoA( A << 1 );
2510 ConstantInt *Solution1 = ConstantInt::get((NegB + SqrtVal).sdiv(TwoA));
2511 ConstantInt *Solution2 = ConstantInt::get((NegB - SqrtVal).sdiv(TwoA));
2512
Dan Gohman89f85052007-10-22 18:31:58 +00002513 return std::make_pair(SE.getConstant(Solution1),
2514 SE.getConstant(Solution2));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002515 } // end APIntOps namespace
2516}
2517
2518/// HowFarToZero - Return the number of times a backedge comparing the specified
2519/// value to zero will execute. If not computable, return UnknownValue
2520SCEVHandle ScalarEvolutionsImpl::HowFarToZero(SCEV *V, const Loop *L) {
2521 // If the value is a constant
2522 if (SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
2523 // If the value is already zero, the branch will execute zero times.
2524 if (C->getValue()->isZero()) return C;
2525 return UnknownValue; // Otherwise it will loop infinitely.
2526 }
2527
2528 SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(V);
2529 if (!AddRec || AddRec->getLoop() != L)
2530 return UnknownValue;
2531
2532 if (AddRec->isAffine()) {
2533 // If this is an affine expression the execution count of this branch is
2534 // equal to:
2535 //
2536 // (0 - Start/Step) iff Start % Step == 0
2537 //
2538 // Get the initial value for the loop.
2539 SCEVHandle Start = getSCEVAtScope(AddRec->getStart(), L->getParentLoop());
2540 if (isa<SCEVCouldNotCompute>(Start)) return UnknownValue;
2541 SCEVHandle Step = AddRec->getOperand(1);
2542
2543 Step = getSCEVAtScope(Step, L->getParentLoop());
2544
2545 // Figure out if Start % Step == 0.
2546 // FIXME: We should add DivExpr and RemExpr operations to our AST.
2547 if (SCEVConstant *StepC = dyn_cast<SCEVConstant>(Step)) {
2548 if (StepC->getValue()->equalsInt(1)) // N % 1 == 0
Dan Gohman89f85052007-10-22 18:31:58 +00002549 return SE.getNegativeSCEV(Start); // 0 - Start/1 == -Start
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002550 if (StepC->getValue()->isAllOnesValue()) // N % -1 == 0
2551 return Start; // 0 - Start/-1 == Start
2552
2553 // Check to see if Start is divisible by SC with no remainder.
2554 if (SCEVConstant *StartC = dyn_cast<SCEVConstant>(Start)) {
2555 ConstantInt *StartCC = StartC->getValue();
2556 Constant *StartNegC = ConstantExpr::getNeg(StartCC);
Nick Lewycky96b38012008-05-25 23:43:32 +00002557 Constant *Rem = ConstantExpr::getURem(StartNegC, StepC->getValue());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002558 if (Rem->isNullValue()) {
Nick Lewycky96b38012008-05-25 23:43:32 +00002559 Constant *Result = ConstantExpr::getUDiv(StartNegC,StepC->getValue());
Dan Gohman89f85052007-10-22 18:31:58 +00002560 return SE.getUnknown(Result);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002561 }
2562 }
2563 }
2564 } else if (AddRec->isQuadratic() && AddRec->getType()->isInteger()) {
2565 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of
2566 // the quadratic equation to solve it.
Dan Gohman89f85052007-10-22 18:31:58 +00002567 std::pair<SCEVHandle,SCEVHandle> Roots = SolveQuadraticEquation(AddRec, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002568 SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
2569 SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
2570 if (R1) {
2571#if 0
2572 cerr << "HFTZ: " << *V << " - sol#1: " << *R1
2573 << " sol#2: " << *R2 << "\n";
2574#endif
2575 // Pick the smallest positive root value.
2576 if (ConstantInt *CB =
2577 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
2578 R1->getValue(), R2->getValue()))) {
2579 if (CB->getZExtValue() == false)
2580 std::swap(R1, R2); // R1 is the minimum root now.
2581
2582 // We can only use this value if the chrec ends up with an exact zero
2583 // value at this index. When solving for "X*X != 5", for example, we
2584 // should not accept a root of 2.
Dan Gohman89f85052007-10-22 18:31:58 +00002585 SCEVHandle Val = AddRec->evaluateAtIteration(R1, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002586 if (SCEVConstant *EvalVal = dyn_cast<SCEVConstant>(Val))
2587 if (EvalVal->getValue()->isZero())
2588 return R1; // We found a quadratic root!
2589 }
2590 }
2591 }
2592
2593 return UnknownValue;
2594}
2595
2596/// HowFarToNonZero - Return the number of times a backedge checking the
2597/// specified value for nonzero will execute. If not computable, return
2598/// UnknownValue
2599SCEVHandle ScalarEvolutionsImpl::HowFarToNonZero(SCEV *V, const Loop *L) {
2600 // Loops that look like: while (X == 0) are very strange indeed. We don't
2601 // handle them yet except for the trivial case. This could be expanded in the
2602 // future as needed.
2603
2604 // If the value is a constant, check to see if it is known to be non-zero
2605 // already. If so, the backedge will execute zero times.
2606 if (SCEVConstant *C = dyn_cast<SCEVConstant>(V)) {
Nick Lewyckyf6805182008-02-21 09:14:53 +00002607 if (!C->getValue()->isNullValue())
2608 return SE.getIntegerSCEV(0, C->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002609 return UnknownValue; // Otherwise it will loop infinitely.
2610 }
2611
2612 // We could implement others, but I really doubt anyone writes loops like
2613 // this, and if they did, they would already be constant folded.
2614 return UnknownValue;
2615}
2616
2617/// HowManyLessThans - Return the number of times a backedge containing the
2618/// specified less-than comparison will execute. If not computable, return
2619/// UnknownValue.
2620SCEVHandle ScalarEvolutionsImpl::
Nick Lewyckyb7c28942007-08-06 19:21:00 +00002621HowManyLessThans(SCEV *LHS, SCEV *RHS, const Loop *L, bool isSigned) {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002622 // Only handle: "ADDREC < LoopInvariant".
2623 if (!RHS->isLoopInvariant(L)) return UnknownValue;
2624
2625 SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(LHS);
2626 if (!AddRec || AddRec->getLoop() != L)
2627 return UnknownValue;
2628
2629 if (AddRec->isAffine()) {
2630 // FORNOW: We only support unit strides.
Dan Gohman89f85052007-10-22 18:31:58 +00002631 SCEVHandle One = SE.getIntegerSCEV(1, RHS->getType());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002632 if (AddRec->getOperand(1) != One)
2633 return UnknownValue;
2634
Wojciech Matyjewiczebc77b12008-02-13 11:51:34 +00002635 // We know the LHS is of the form {n,+,1} and the RHS is some loop-invariant
2636 // m. So, we count the number of iterations in which {n,+,1} < m is true.
2637 // Note that we cannot simply return max(m-n,0) because it's not safe to
Wojciech Matyjewicz1377a542008-02-13 12:21:32 +00002638 // treat m-n as signed nor unsigned due to overflow possibility.
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002639
Wojciech Matyjewiczebc77b12008-02-13 11:51:34 +00002640 // First, we get the value of the LHS in the first iteration: n
2641 SCEVHandle Start = AddRec->getOperand(0);
2642
2643 // Then, we get the value of the LHS in the first iteration in which the
2644 // above condition doesn't hold. This equals to max(m,n).
Nick Lewyckye7a24ff2008-02-20 06:48:22 +00002645 SCEVHandle End = isSigned ? SE.getSMaxExpr(RHS, Start)
2646 : SE.getUMaxExpr(RHS, Start);
Wojciech Matyjewiczebc77b12008-02-13 11:51:34 +00002647
2648 // Finally, we subtract these two values to get the number of times the
2649 // backedge is executed: max(m,n)-n.
Wojciech Matyjewicza5718fc2008-02-12 15:09:36 +00002650 return SE.getMinusSCEV(End, Start);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002651 }
2652
2653 return UnknownValue;
2654}
2655
2656/// getNumIterationsInRange - Return the number of iterations of this loop that
2657/// produce values in the specified constant range. Another way of looking at
2658/// this is that it returns the first iteration number where the value is not in
2659/// the condition, thus computing the exit count. If the iteration count can't
2660/// be computed, an instance of SCEVCouldNotCompute is returned.
Dan Gohman89f85052007-10-22 18:31:58 +00002661SCEVHandle SCEVAddRecExpr::getNumIterationsInRange(ConstantRange Range,
2662 ScalarEvolution &SE) const {
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002663 if (Range.isFullSet()) // Infinite loop.
2664 return new SCEVCouldNotCompute();
2665
2666 // If the start is a non-zero constant, shift the range to simplify things.
2667 if (SCEVConstant *SC = dyn_cast<SCEVConstant>(getStart()))
2668 if (!SC->getValue()->isZero()) {
2669 std::vector<SCEVHandle> Operands(op_begin(), op_end());
Dan Gohman89f85052007-10-22 18:31:58 +00002670 Operands[0] = SE.getIntegerSCEV(0, SC->getType());
2671 SCEVHandle Shifted = SE.getAddRecExpr(Operands, getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002672 if (SCEVAddRecExpr *ShiftedAddRec = dyn_cast<SCEVAddRecExpr>(Shifted))
2673 return ShiftedAddRec->getNumIterationsInRange(
Dan Gohman89f85052007-10-22 18:31:58 +00002674 Range.subtract(SC->getValue()->getValue()), SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002675 // This is strange and shouldn't happen.
2676 return new SCEVCouldNotCompute();
2677 }
2678
2679 // The only time we can solve this is when we have all constant indices.
2680 // Otherwise, we cannot determine the overflow conditions.
2681 for (unsigned i = 0, e = getNumOperands(); i != e; ++i)
2682 if (!isa<SCEVConstant>(getOperand(i)))
2683 return new SCEVCouldNotCompute();
2684
2685
2686 // Okay at this point we know that all elements of the chrec are constants and
2687 // that the start element is zero.
2688
2689 // First check to see if the range contains zero. If not, the first
2690 // iteration exits.
2691 if (!Range.contains(APInt(getBitWidth(),0)))
Dan Gohman89f85052007-10-22 18:31:58 +00002692 return SE.getConstant(ConstantInt::get(getType(),0));
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002693
2694 if (isAffine()) {
2695 // If this is an affine expression then we have this situation:
2696 // Solve {0,+,A} in Range === Ax in Range
2697
2698 // We know that zero is in the range. If A is positive then we know that
2699 // the upper value of the range must be the first possible exit value.
2700 // If A is negative then the lower of the range is the last possible loop
2701 // value. Also note that we already checked for a full range.
2702 APInt One(getBitWidth(),1);
2703 APInt A = cast<SCEVConstant>(getOperand(1))->getValue()->getValue();
2704 APInt End = A.sge(One) ? (Range.getUpper() - One) : Range.getLower();
2705
2706 // The exit value should be (End+A)/A.
Nick Lewyckya0facae2007-09-27 14:12:54 +00002707 APInt ExitVal = (End + A).udiv(A);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002708 ConstantInt *ExitValue = ConstantInt::get(ExitVal);
2709
2710 // Evaluate at the exit value. If we really did fall out of the valid
2711 // range, then we computed our trip count, otherwise wrap around or other
2712 // things must have happened.
Dan Gohman89f85052007-10-22 18:31:58 +00002713 ConstantInt *Val = EvaluateConstantChrecAtConstant(this, ExitValue, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002714 if (Range.contains(Val->getValue()))
2715 return new SCEVCouldNotCompute(); // Something strange happened
2716
2717 // Ensure that the previous value is in the range. This is a sanity check.
2718 assert(Range.contains(
2719 EvaluateConstantChrecAtConstant(this,
Dan Gohman89f85052007-10-22 18:31:58 +00002720 ConstantInt::get(ExitVal - One), SE)->getValue()) &&
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002721 "Linear scev computation is off in a bad way!");
Dan Gohman89f85052007-10-22 18:31:58 +00002722 return SE.getConstant(ExitValue);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002723 } else if (isQuadratic()) {
2724 // If this is a quadratic (3-term) AddRec {L,+,M,+,N}, find the roots of the
2725 // quadratic equation to solve it. To do this, we must frame our problem in
2726 // terms of figuring out when zero is crossed, instead of when
2727 // Range.getUpper() is crossed.
2728 std::vector<SCEVHandle> NewOps(op_begin(), op_end());
Dan Gohman89f85052007-10-22 18:31:58 +00002729 NewOps[0] = SE.getNegativeSCEV(SE.getConstant(Range.getUpper()));
2730 SCEVHandle NewAddRec = SE.getAddRecExpr(NewOps, getLoop());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002731
2732 // Next, solve the constructed addrec
2733 std::pair<SCEVHandle,SCEVHandle> Roots =
Dan Gohman89f85052007-10-22 18:31:58 +00002734 SolveQuadraticEquation(cast<SCEVAddRecExpr>(NewAddRec), SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002735 SCEVConstant *R1 = dyn_cast<SCEVConstant>(Roots.first);
2736 SCEVConstant *R2 = dyn_cast<SCEVConstant>(Roots.second);
2737 if (R1) {
2738 // Pick the smallest positive root value.
2739 if (ConstantInt *CB =
2740 dyn_cast<ConstantInt>(ConstantExpr::getICmp(ICmpInst::ICMP_ULT,
2741 R1->getValue(), R2->getValue()))) {
2742 if (CB->getZExtValue() == false)
2743 std::swap(R1, R2); // R1 is the minimum root now.
2744
2745 // Make sure the root is not off by one. The returned iteration should
2746 // not be in the range, but the previous one should be. When solving
2747 // for "X*X < 5", for example, we should not return a root of 2.
2748 ConstantInt *R1Val = EvaluateConstantChrecAtConstant(this,
Dan Gohman89f85052007-10-22 18:31:58 +00002749 R1->getValue(),
2750 SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002751 if (Range.contains(R1Val->getValue())) {
2752 // The next iteration must be out of the range...
2753 ConstantInt *NextVal = ConstantInt::get(R1->getValue()->getValue()+1);
2754
Dan Gohman89f85052007-10-22 18:31:58 +00002755 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002756 if (!Range.contains(R1Val->getValue()))
Dan Gohman89f85052007-10-22 18:31:58 +00002757 return SE.getConstant(NextVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002758 return new SCEVCouldNotCompute(); // Something strange happened
2759 }
2760
2761 // If R1 was not in the range, then it is a good return value. Make
2762 // sure that R1-1 WAS in the range though, just in case.
2763 ConstantInt *NextVal = ConstantInt::get(R1->getValue()->getValue()-1);
Dan Gohman89f85052007-10-22 18:31:58 +00002764 R1Val = EvaluateConstantChrecAtConstant(this, NextVal, SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002765 if (Range.contains(R1Val->getValue()))
2766 return R1;
2767 return new SCEVCouldNotCompute(); // Something strange happened
2768 }
2769 }
2770 }
2771
2772 // Fallback, if this is a general polynomial, figure out the progression
2773 // through brute force: evaluate until we find an iteration that fails the
2774 // test. This is likely to be slow, but getting an accurate trip count is
2775 // incredibly important, we will be able to simplify the exit test a lot, and
2776 // we are almost guaranteed to get a trip count in this case.
2777 ConstantInt *TestVal = ConstantInt::get(getType(), 0);
2778 ConstantInt *EndVal = TestVal; // Stop when we wrap around.
2779 do {
2780 ++NumBruteForceEvaluations;
Dan Gohman89f85052007-10-22 18:31:58 +00002781 SCEVHandle Val = evaluateAtIteration(SE.getConstant(TestVal), SE);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002782 if (!isa<SCEVConstant>(Val)) // This shouldn't happen.
2783 return new SCEVCouldNotCompute();
2784
2785 // Check to see if we found the value!
2786 if (!Range.contains(cast<SCEVConstant>(Val)->getValue()->getValue()))
Dan Gohman89f85052007-10-22 18:31:58 +00002787 return SE.getConstant(TestVal);
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002788
2789 // Increment to test the next index.
2790 TestVal = ConstantInt::get(TestVal->getValue()+1);
2791 } while (TestVal != EndVal);
2792
2793 return new SCEVCouldNotCompute();
2794}
2795
2796
2797
2798//===----------------------------------------------------------------------===//
2799// ScalarEvolution Class Implementation
2800//===----------------------------------------------------------------------===//
2801
2802bool ScalarEvolution::runOnFunction(Function &F) {
Dan Gohman89f85052007-10-22 18:31:58 +00002803 Impl = new ScalarEvolutionsImpl(*this, F, getAnalysis<LoopInfo>());
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002804 return false;
2805}
2806
2807void ScalarEvolution::releaseMemory() {
2808 delete (ScalarEvolutionsImpl*)Impl;
2809 Impl = 0;
2810}
2811
2812void ScalarEvolution::getAnalysisUsage(AnalysisUsage &AU) const {
2813 AU.setPreservesAll();
2814 AU.addRequiredTransitive<LoopInfo>();
2815}
2816
2817SCEVHandle ScalarEvolution::getSCEV(Value *V) const {
2818 return ((ScalarEvolutionsImpl*)Impl)->getSCEV(V);
2819}
2820
2821/// hasSCEV - Return true if the SCEV for this value has already been
2822/// computed.
2823bool ScalarEvolution::hasSCEV(Value *V) const {
2824 return ((ScalarEvolutionsImpl*)Impl)->hasSCEV(V);
2825}
2826
2827
2828/// setSCEV - Insert the specified SCEV into the map of current SCEVs for
2829/// the specified value.
2830void ScalarEvolution::setSCEV(Value *V, const SCEVHandle &H) {
2831 ((ScalarEvolutionsImpl*)Impl)->setSCEV(V, H);
2832}
2833
2834
2835SCEVHandle ScalarEvolution::getIterationCount(const Loop *L) const {
2836 return ((ScalarEvolutionsImpl*)Impl)->getIterationCount(L);
2837}
2838
2839bool ScalarEvolution::hasLoopInvariantIterationCount(const Loop *L) const {
2840 return !isa<SCEVCouldNotCompute>(getIterationCount(L));
2841}
2842
2843SCEVHandle ScalarEvolution::getSCEVAtScope(Value *V, const Loop *L) const {
2844 return ((ScalarEvolutionsImpl*)Impl)->getSCEVAtScope(getSCEV(V), L);
2845}
2846
2847void ScalarEvolution::deleteValueFromRecords(Value *V) const {
2848 return ((ScalarEvolutionsImpl*)Impl)->deleteValueFromRecords(V);
2849}
2850
2851static void PrintLoopInfo(std::ostream &OS, const ScalarEvolution *SE,
2852 const Loop *L) {
2853 // Print all inner loops first
2854 for (Loop::iterator I = L->begin(), E = L->end(); I != E; ++I)
2855 PrintLoopInfo(OS, SE, *I);
2856
Nick Lewyckye5da1912008-01-02 02:49:20 +00002857 OS << "Loop " << L->getHeader()->getName() << ": ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002858
Devang Patel02451fa2007-08-21 00:31:24 +00002859 SmallVector<BasicBlock*, 8> ExitBlocks;
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002860 L->getExitBlocks(ExitBlocks);
2861 if (ExitBlocks.size() != 1)
Nick Lewyckye5da1912008-01-02 02:49:20 +00002862 OS << "<multiple exits> ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002863
2864 if (SE->hasLoopInvariantIterationCount(L)) {
Nick Lewyckye5da1912008-01-02 02:49:20 +00002865 OS << *SE->getIterationCount(L) << " iterations! ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002866 } else {
Nick Lewyckye5da1912008-01-02 02:49:20 +00002867 OS << "Unpredictable iteration count. ";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002868 }
2869
Nick Lewyckye5da1912008-01-02 02:49:20 +00002870 OS << "\n";
Dan Gohmanf17a25c2007-07-18 16:29:46 +00002871}
2872
2873void ScalarEvolution::print(std::ostream &OS, const Module* ) const {
2874 Function &F = ((ScalarEvolutionsImpl*)Impl)->F;
2875 LoopInfo &LI = ((ScalarEvolutionsImpl*)Impl)->LI;
2876
2877 OS << "Classifying expressions for: " << F.getName() << "\n";
2878 for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I)
2879 if (I->getType()->isInteger()) {
2880 OS << *I;
2881 OS << " --> ";
2882 SCEVHandle SV = getSCEV(&*I);
2883 SV->print(OS);
2884 OS << "\t\t";
2885
2886 if ((*I).getType()->isInteger()) {
2887 ConstantRange Bounds = SV->getValueRange();
2888 if (!Bounds.isFullSet())
2889 OS << "Bounds: " << Bounds << " ";
2890 }
2891
2892 if (const Loop *L = LI.getLoopFor((*I).getParent())) {
2893 OS << "Exits: ";
2894 SCEVHandle ExitValue = getSCEVAtScope(&*I, L->getParentLoop());
2895 if (isa<SCEVCouldNotCompute>(ExitValue)) {
2896 OS << "<<Unknown>>";
2897 } else {
2898 OS << *ExitValue;
2899 }
2900 }
2901
2902
2903 OS << "\n";
2904 }
2905
2906 OS << "Determining loop execution counts for: " << F.getName() << "\n";
2907 for (LoopInfo::iterator I = LI.begin(), E = LI.end(); I != E; ++I)
2908 PrintLoopInfo(OS, this, *I);
2909}